首页 > 解决方案 > 角度:输入“可观察”' 没有兼容的调用签名

问题描述

我还在学习角度,我想用一个布尔可观察对象提供服务,并订阅该可观察对象。

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

所以在我的登录服务中:

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

在我的组件中我使用这个功能

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

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

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

不知道出了什么问题。但作为一个新手,我需要说我不太了解 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"
}

标签: angularangular2-observablesbehaviorsubject

解决方案


您使用此 getter将 isLoggedIn 定义为属性:

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

但是然后您将其称为函数

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

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

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

推荐阅读