【问题标题】:Angular: Type 'Observable<boolean>' has no compatible call signaturesAngular:类型 'Observable<boolean>' 没有兼容的调用签名
【发布时间】:2018-12-08 20:06:22
【问题描述】:

我仍在学习 Angular,我想使用布尔可观察对象创建服务,并订阅该可观察对象。

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

所以在我的登录服务中:

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"
}

【问题讨论】:

  • 您使用的是哪个版本的 Angular?因为我看到public http: Http,现在Angular 推荐使用http: HttpClient,如下所述:https://angular.io/guide/http
  • 我添加了部分 package.json 以显示使用的版本
  • 如果最新版本是 Angular 7,为什么还要使用这个过时的 Angular 4 版本?
  • 我在大学收到了这个网络应用程序来学习和学习。我无法更新它,我必须使用我收到的内容。不是我的选择。已经开发了几个部分,并且它们工作正常。现在我必须进行一些更改,但我不能,因为我从我的代码中收到了该错误。

标签: angular angular2-observables behaviorsubject


【解决方案1】:

你用这个 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;
    })
  );

【讨论】:

  • 非常感谢!这很明显,但我看不到它,而且我浪费了很多时间。现在它完美地工作了。谢谢。
猜你喜欢
  • 2017-12-29
  • 2017-03-20
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多