[英]Error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value
[英]Ts Error : A function whose declared type is neither 'void' nor 'any' must return a value. when return statements are inside a subscribe method
我在Angular 2項目中做了一個簡單的服務,用於檢查用戶是否登錄。 它檢查FirebaseAuth對象中是否存在用戶對象。 但是,當我的return語句實際上位於auth變量的subscription方法內時,函數聲明會為“缺少return語句”引發錯誤。 代碼看起來像這樣:
import { Component, OnInit , Injectable} from '@angular/core';
import { FirebaseAuthState, FirebaseAuth} from "angularfire2";
@Injectable()
export class CheckLogged {
constructor(private auth:FirebaseAuth ){}
check(): boolean{
this.auth.subscribe((user: FirebaseAuthState) => {
if (user) {
return true;
}
return false;
})
}
}
“ check():boolean”語句引發此錯誤
我在組件的OnInit生命周期掛鈎中調用我的函數並將其分配給變量
this.loggedIn = this.CheckLogged.check();
check(): boolean{ // <<<== no boolean is returned from this function
this.auth.subscribe((user: FirebaseAuthState) => {
if (user) {
return true;
}
return false;
})
}
在上面的代碼中, return xxx
僅從傳遞給subscribe(...)
的回調中返回,而不是從check
返回。
您無法從異步切換回同步。 該方法應該看起來像
check(): Observable<boolean>{ // <<<== no boolean is returned from this function
return this.auth.map((user: FirebaseAuthState) => {
if (user) {
return true;
}
return false;
})
}
然后調用者需要訂閱返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.