Search code examples
angulartypescriptangular-components

Angular Observable don't set local variable while calling API


I'm trying to set value in a local variable like this:

export class memberComponent implements OnInit {

   member : Member = new Member();
   constructor(private memberService: MemberService) {}

   ngOnInit() {
     this.loadMember();
     console.log("member 1: ", this.member); // in here member is empty
   }

   loadMember(){
     this.memberService.getMember("john").subscribe(mem => {
       this.member = mem;
       console.log("member 2: ", this.member);// in here member is NOT empty
     });
   }
}

And because the member is empty nothing shows in the page. Here is my component.html

<h1>{{member.userName}}</h1>

Finally, this is the memberService:

export class MemberService {

  baseUrl = environment.apiUrl;

  constructor(private http: HttpClient) {}

  getMember(userName: string) {
    return  this.http.get<Member>(this.baseUrl + 'users/' + userName);
  }

}

I tried to user pipe(take(1)) method and interface instead of class but there were no difference. And nothing has shown in my html page.

What's the problem and how can I fix it?


Solution

  • You should be receiving a can't read userName of undefined error in browser console. to fix this try use elvis operator like below :-

    <h1>{{member?.userName}}</h1>