角度:类型“ Observable <boolean>”没有兼容的呼叫签名

Ale*_*lex 0 behaviorsubject angular2-observables angular

我仍在学习有角度的东西,我想提供一个具有布尔可观察值的服务,并订阅该可观察值。

我遵循了本教程,因为我真正想要的是在用户未登录时隐藏菜单导航链接,并且本教程几乎相同。

因此,在我的登录服务中:

export class LoginService {

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

  get isLoggedIn() {
    console.log(this.loggedIn);
    return this.loggedIn.asObservable();
  }

  constructor(
    public http: Http,
    public utilsService: UtilsService) { }

  public login(credentials: Credentials): Observable<Response> {
    // login code
    // if user succeed login then:
    this.loggedIn.next(true);
  }

  public logout(): Observable<Response> {
    // logout code
    // if user succeed logout then:
    this.loggedIn.next(false);
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我使用此功能

public isLoggedIn: boolean;

userIsLoggedIn() {

  this._login.isLoggedIn().subscribe(
    ((res: boolean) => {
        console.log(res);
        this.isLoggedIn = res;
    })
  );

}  // <- this is (36,5) position returned from error log
Run Code Online (Sandbox Code Playgroud)

如果一切正常,则*ngIf="isLoggedIn"在组件模板的nav链接中使用简单的名称应该可以工作。但是出了点问题,尝试编译时出现下一个错误。

/project-folder/src/app/shared/navbar/navbar.ts中的错误(36,5):无法调用类型缺少调用签名的表达式。类型“可观察”没有兼容的呼叫签名。

不知道怎么了 但是作为一个新手,我需要说的是我不太了解BehaviorSubject是什么,并且还没有找到关于它的良好而易于理解的文档。

它应该很容易,但是在尝试了几天却没有成功之后,我几乎放弃了隐藏未登录用户的链接。

编辑:我添加package.json的一部分以显示使用的版本:

"devDependencies": {
  "@angular/cli": "1.4.5",
  "@angular/compiler-cli": "4.4.4",
  "@angular/language-service": "4.4.4",
  "@types/node": "6.0.60",
  "codelyzer": "3.2.0",
  // some of the dependencies omitted
  "gulp": "3.9.1",
  "gulp-coveralls": "0.1.4",
  "typescript": "2.3.3"
}
Run Code Online (Sandbox Code Playgroud)

Deb*_*ahK 6

您可以使用以下方法将isLoggedIn定义为属性

  get isLoggedIn() {
    console.log(this.loggedIn);
    return this.loggedIn.asObservable();
  }
Run Code Online (Sandbox Code Playgroud)

但是随后您将其称为函数

  this._login.isLoggedIn().subscribe(
    ((res: boolean) => {
        console.log(res);
        this.isLoggedIn = res;
    })
  );
Run Code Online (Sandbox Code Playgroud)

您需要改为将其作为属性访问:

  this._login.isLoggedIn.subscribe(  // No () here
    ((res: boolean) => {
        console.log(res);
        this.isLoggedIn = res;
    })
  );
Run Code Online (Sandbox Code Playgroud)