user4661780
user4661780

Reputation:

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?

Upvotes: 0

Views: 173

Answers (1)

Aakash Garg
Aakash Garg

Reputation: 10979

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>

Upvotes: 0

Related Questions