Angular2:如何让布尔函数返回从subscribe函数派生的变量?
如何让下面的函数返回this.loggedIn变量Angular2:如何让布尔函数返回从subscribe函数派生的变量?,angular,typescript,Angular,Typescript,如何让下面的函数返回this.loggedIn变量 autho(): boolean{ this.http.get("http://localhost:1337/session").map(res => res.json()).subscribe( data => this.loggedIn = data.authenticated, err => console.log(err), () => con
autho(): boolean{
this.http.get("http://localhost:1337/session").map(res => res.json()).subscribe(
data => this.loggedIn = data.authenticated,
err => console.log(err),
() => console.log('autho API response ', this.loggedIn)
)
return this.loggedIn; // I am getting undefined
}
假设http类的成员是angular2 http服务的实例,那么您的问题是一个基本的异步问题
(“http://localhost:1337/session“”
返回一个可观察的流,该流是一个对象,提供了绑定处理函数解析的回调的能力。此解决方案是异步的,这意味着您不能像您所做的那样直接返回loggedIn
。在此步骤中,尚未调用订阅回调
您有很多方法来实现您不想实现的功能,但请务必了解代码的异步状态。
我建议你把你的观察转化为一个承诺,这个承诺可以被锁住并返回
@Injectable()
class FooBar {
...
constructor(private http:Http) {}
...
authO():Promise {
return this.http.get('http://localhost:1337/session')
.toPromise()
.then((response:Response) => response.json())
.then((data) => {
return this.loggedIn = data.authenticated;
});
}
}
//usage
@Component({...})
class FooBarComponent {
constructor(private foobarService:FooBar) {
}
auth() {
this.foobarService.auth0()
.then((loogedIn) => {
// do some stuff
})
.catch((err) => {
console.error(err);
});
}
}
您可以保持可观察状态并使用订阅模式,但在我看来,当一个事件可以被多次触发时,可观察/观察模式确实很有用。http进程只能触发订阅处理程序一次,并且不能链接,因此在这种情况下,承诺更好
确保要求rxjs的toPromise
操作员使上述示例正常工作
无论如何,您的主要问题是尝试同步使用观察者,而这目前无法完成。您好,您的问题有点混乱。您能否向我们提供包含该属性的组件,并向我们展示您的组件结构。其中包含另一个。。。没有这些信息我们帮不了你