Sarl sbeer
Sarl sbeer

Reputation: 55

rxjs observable in angular

I have a confusion about the observable in rxjs Is it follow the observer design pattern? if so, Should its subscriber get notified of the latest value or any change?

Let me show you an example.

this is my user service

    login(userData): Observable<any> {
    return this.http.post(this.APIURL,userData).pipe(
      map((user: any) => user.firstName),
      tap((name) => {
        localStorage.setItem('userName', name);
        localStorage.setItem('isLogin', 'true');
      })
      );
    }
   private nameObservable:Observable<string>=new Observable<string>(observer=>{
      observer.next(localStorage.getItem("userName"))
    })
    getName(): Observable<string> {
      return this.nameObservable;
    }
    logout() {
      localStorage.removeItem("userName");
      localStorage.removeItem("isLogin");
    }

this is my header component

    ngOnInit() {
   this.isLogin=!!localStorage.getItem("isLogin")
    this.userService.getName()
    .subscribe((userName)=>{
         this.name=userName
       })
   }

and login button call that login function

the issue is my header doesn't get notified when I hit the login button it needs to be reloaded. I know I should use Subject or behaviorSubject instead of observable but my question again is:

Upvotes: 0

Views: 140

Answers (1)

Joosep Parts
Joosep Parts

Reputation: 6245

There appears to be a typo. You are setting an item on key username but then asking for userName try fixing that. A little bit clunky with the manual subscribe(), but it should work. Remember to unsubscribe as well.

Upvotes: 0

Related Questions