0

I'm using angular 6, now I'm updating my resource istance in this way

this.user = api.getUser();

public getUser(): User {
  const myHeader = new HttpHeaders({
    'Authorization': 'Basic ' + this.session.getAccessToken(),
  }).append('Content-Type', 'application/json');
  this.http.get < User > (API_URL + '/users', {
      headers: myHeader
    })
    .pipe(
      catchError(this.handleError('get-user', [])))
    .subscribe((response) => {
      return <User > response;
    });
  return null;
}

my issue is that my response firse return null, and later return my response istance.. how I can provide a soluction for this?

Thank you

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • you are returning null and then the result. Remove `return null;` and it will works fine. also you shouldn't subscribe in the service. You should remove the `.subscribe` and add `return this.http.get(...)` and subscribing in a component. – Jacopo Sciampi Dec 03 '18 at 16:09
  • It says I must return something... – Alesandro Giordano Dec 03 '18 at 16:10
  • @AlesandroGiordano updated my answer here above. If you are not familiar with angular have a look at this: https://angular.io/tutorial/toh-pt4 – Jacopo Sciampi Dec 03 '18 at 16:15

3 Answers3

1

Your getUser method should return an Observable<User>. Something like this:

public getUser(): Observable<User> {

  const myHeader = new HttpHeaders({
    'Authorization': 'Basic ' + this.session.getAccessToken(),
  })
  .append('Content-Type', 'application/json');

  return this.http.get<User>(API_URL + '/users', { headers: myHeader })
    .pipe(
      catchError(this.handleError('get-user', []))
    );
}

You should subscribe to this Observable<User> to get the user when you're calling api.getUser(). Like this:

api.getUser()
  .subscribe(response => this.user = response);
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
-1
public getUser(): Observable<User> {
    const myHeader = new HttpHeaders({
      'Authorization': 'Basic ' + this.session.getAccessToken(),
    }).append('Content-Type', 'application/json');

    return this.http
      .get<User>(API_URL + '/users', {headers: myHeader})
      .pipe(
        catchError(this.handleError('get-user', []))
      );
  }



api.getUser().subscribe(user => this.user = user);
epsilon
  • 868
  • 2
  • 8
  • 17
-1

What you need to do is set the value of this.user asynchronously. Instead of subscribing to your http call within the getUser method, you should return the Observable from the method. It would look something like this:

public getUser(): Observable<User> {
    const myHeader = new HttpHeaders({
      'Authorization': 'Basic ' + this.session.getAccessToken(),
    }).append('Content-Type', 'application/json');
    return this.http.get<User>(API_URL + '/users', {headers: myHeader})
      .pipe(
      catchError(this.handleError('get-user', [])));
}

getUser().subscribe((user) => this.user = user);

Hope that helps!

rozza2058
  • 560
  • 1
  • 3
  • 11