angularhttphttpresponseangular-httpangular-httpclient

How to fetch data in Angular


can someone help me with getting number from http response in Angular 5 ? I don't now how to do it, I was searching at internet but Angular grow very fast so it doesn't help me. Thanks for any help !

My code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../entities/User';

@Injectable()
export class UserService {

  private usersurl: 'http://localhost:8080/api/users';

  user: User;
  id: number;

  constructor(private http: HttpClient) {}

  isLoggedIn() {
    return this.user != null;
  }

  isAdmin() {
    return this.user.isAdmin;
  }

  unLoggin() {
    this.user = null;
  }

  login(username: string, password: string) {
    this.id = null;
    this.http.get<number>(`${this.usersurl}/verify?username=${username}&password=${password}`).subscribe(id => this.id = id);
    alert(this.id);
    if (this.id != null) {
      return true;
    } else {
      return false;
    }
  }

}

It alert [object Object] localhost:8080/api/users/verify returns for example 8 only 8 no json formated 8


Solution

  • To make a Http call inside of Angular we can use the HttpClient. This requires us to import the HttpClientModule inside of our root module (app.module.ts):

    import { HttpClientModule } from '@angular/common/http';
    import { DataService } from './data.service';
    
    // Omitted other dependencies for brevity
    @NgModule({
      imports: [HttpClientModule],
      providers: [DataService],
    })
    export class AppModule {}
    

    Inside of our service (i.e. data.service.ts) which we've registered as a provider, we can inject HttpClient and use the get method:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable()
    export class DataService {
      ROOT_URL = 'http://your-api.com';
    
      constructor(private http: HttpClient) {}
    
      getUserId(username: string, password: string) {
        return this.http
          .get<number>(`${this.ROOT_URL}/verify?username=${username}&password=${password}`)
      }
    }
    

    Inside of our Component we can then subscribe to the Observable emitted from our service:

    import { Component, OnInit } from '@angular/core';
    import { DataService } from './data.service';
    
    @Component({
      selector: 'app-root',
      template: `
        <h1>UserId: {{userId}}</h1>
      `,
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements OnInit {
      userId: number;
    
      constructor(private dataService: DataService) {}
    
      ngOnInit() {
        this.dataService
          .getUserId('test', 'password')
          .subscribe(id => this.userId = id);
      }
    }
    

    Alternatively, we can use the Async pipe to let Angular handle the subscription:

    import { Component, OnInit } from '@angular/core';
    import { DataService } from './data.service';
    import { Observable } from 'rxjs/Observable';
    
    @Component({
      selector: 'app-root',
      template: `
        <h1>UserId: {{userId$ | async}}</h1>
      `,
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements OnInit {
      userId$: Observable<Number>;
    
      constructor(private dataService: DataService) {}
    
      ngOnInit() {
        this.userId$ = this.dataService.getUserId('test', 'password');
      }
    }