简体   繁体   中英

Angular BehaviorSubject; the “next” method doesn't work

I have a code that I wrote back in Angular 4 and it worked perfectly, now part of it is broken in Angular 6 and I appreciate some help.

I have an AuthService class:

export class AuthService {

    private loggedIn = new BehaviorSubject<boolean>(false);

    isUserLoggedIn(): Observable<boolean> {
        return this.loggedIn.asObservable();
    }

    isUserLoggedIn(): Observable<boolean> {
        return this.loggedIn.asObservable();
    }

    login(username: string, password: string) {
        let body =
        {
            username: username,
            password: password
        };

        return this._http.post(Settings.apiEndpoint + "users/authenticate", body)
            .map(res => {
                localStorage.setItem('token', res["token"]);
                localStorage.setItem('username', res["username"]);
                this.isLoggedIn = true;
                this.loggedIn.next(true);
                return res;
            })
            .catch(error => {
                this.clearAuthData();
                return Observable.throw(error)
            });
    }

    logout() {
        localStorage.clear();
        this.isLoggedIn = false;
        this.loggedIn.next(this.isLoggedIn);
    }
}

and in my AppComponent , I subscribe to this subject like this in the ngOnInit:

this._auth.isUserLoggedIn()
            .subscribe(
                d => {
                    console.log("d here", d);
                    if (d)
                    {
                        this.isLoggedIn = true;
                        this.username = this._auth.getUsername();
                    }
                    else {
                        this.isLoggedIn = false;
                    }
                },
                d => {
                    console.log("error.");
                },
                () => {
                  console.log("bull.");
                }
            );

The issue is when I logout, the AppComponent does react to the observable, but when I login it doesn't. The code is untouched as far as I can tell from what it was in Angular 4, so I cannot figure out why it is not firing.

Your code doesn't work beause of rxjs 6 breaking change, version 5.5 introduced pipeable operators

Before:

source.map(x => x * 2).catch(() => of('ups'))

Now:

source.pipe(map(x => x * 2), catchError(() => of('ups')))

also they moved catch() to catchError(), do() to tap(), switch() to switchAll() and finally() to finalize()

[Edit] don't forget to import your rxjs operators like that: import { map } from 'rxjs/operators';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM