typescript Ts 错误:声明类型既不是“void”也不是“any”的函数必须返回一个值。当 return 语句位于 subscribe 方法中时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41878372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ts Error : A function whose declared type is neither 'void' nor 'any' must return a value. when return statements are inside a subscribe method
提问by Veer Singh
I've made a simple service in my Angular 2 project for checking if the user is logged in or not. It checks if the user object exists within the FirebaseAuth object. But the function declaration throws an error for the "lack of return statement" when actually my return statements are inside the subscribe method on the auth variable. Code looks something like this:
我在我的 Angular 2 项目中做了一个简单的服务来检查用户是否登录。它检查用户对象是否存在于 FirebaseAuth 对象中。但是当实际上我的 return 语句位于 auth 变量的 subscribe 方法内时,函数声明会因“缺少 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;
})
}
}
The "check():boolean" statement throws this error
“check():boolean”语句抛出这个错误
Im calling my function inside an OnInit lifecycle hook in a component and assigning it to a variable
我在组件的 OnInit 生命周期钩子内调用我的函数并将其分配给一个变量
this.loggedIn = this.CheckLogged.check();
回答by Günter Z?chbauer
check(): boolean{ // <<<== no boolean is returned from this function
this.auth.subscribe((user: FirebaseAuthState) => {
if (user) {
return true;
}
return false;
})
}
In above code return xxx
only returns from the callback passed to subscribe(...)
, but doesn't return from check
.
在上面的代码中,return xxx
只从传递给 的回调返回subscribe(...)
,但不从 返回check
。
You can't switch from async back to sync. The method should look like
您无法从异步切换回同步。该方法应该看起来像
check(): Observable<boolean>{ // <<<== no boolean is returned from this function
return this.auth.map((user: FirebaseAuthState) => {
if (user) {
return true;
}
return false;
})
}
and then the caller needs to subscribe to the return value.
然后调用者需要订阅返回值。