首页 > 解决方案 > 角度行为主题;“下一个”方法不起作用

问题描述

我有一个我在 Angular 4 中写回的代码,它运行良好,现在它的一部分在 Angular 6 中被破坏了,我感谢一些帮助。

我有一AuthService堂课:

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);
    }
}

在我AppComponent的 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.");
                }
            );

问题是当我注销时,AppComponent 确实对 observable 做出反应,但是当我登录时它没有。据我所知,代码在 Angular 4 中的内容没有受到影响,所以我无法弄清楚为什么它没有触发。

标签: angulartypescriptangular6observablereactive-extensions-js

解决方案


由于 rxjs 6 重大更改,您的代码不起作用,版本 5.5 引入了可管道操作符

前:

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

现在:

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

他们还将 catch() 移至 catchError(),将 do() 移至 tap(),将 switch() 移至 switchAll(),将 finally() 移至 finalize()

[编辑] 不要忘记像这样导入你的 rxjs 操作符: import { map } from 'rxjs/operators';


推荐阅读