Jus*_*ode 4 service angular-services angular-components angular angular5
所以,我试图解决这个问题.但是,不知怎的,我无法这样做,可能是因为角度5缺乏知识.这是我的服务:
GetCurrentUserData(): Observable<ResponseData> {
return this.http.get<ResponseData>(ApplicationURLS.GetCurrentUserInformation)
.map(response => {
return response;
});
//.catch(error => this.handleError(error));
}
Run Code Online (Sandbox Code Playgroud)
这是我的组成部分:
public GetCurrentUserInformation(): any {
return this.loginService.GetCurrentUserData().subscribe(data => { return data; });
}
Run Code Online (Sandbox Code Playgroud)
在这里,我试图访问数据:
ngAfterViewInit() {
debugger;
this.responseData = this.GetCurrentUserInformation();
if (this.responseData.code != responseCodes.success) {
this.googleInit();
}
}
Run Code Online (Sandbox Code Playgroud)
当我检查this.responseData时,它总是返回此而不是我想要的数据:

我只想进行同步调用,这样我就可以立即获取数据.
我也尝试在服务中使用do()但它返回的do()不是函数.
mal*_*awi 26
这可以通过使用来简化 async/await
public GetCurrentUserInformation(): Promise<any>{
return this.loginService.GetCurrentUserData().toPromise()
}
Run Code Online (Sandbox Code Playgroud)
ngAfterViewInit
async ngAfterViewInit() {
this.responseData = await this.GetCurrentUserInformation(); // ???
if (this.responseData.code != responseCodes.success) {
this.googleInit();
}
}
Run Code Online (Sandbox Code Playgroud)
订阅GetCurrentUserData()http调用是异步的(每个浏览器api调用都是异步的,因为javascript引擎在单个线程中运行(google for browser event loop for more,这不是一个有角度的问题))
this.GetCurrentUserInformation().subscribe((data: ResponseData) => {
if (this.responseData.code != responseCodes.success) {
this.googleInit();
}
});
Run Code Online (Sandbox Code Playgroud)
不能同步调用异步函数,因为它们是异步的。
subscribe通常不应在预期被链接的方法中执行。即使应该,也应该从方法返回可观察而不是订阅(订阅可以另外保存以在销毁时取消订阅)。
GetCurrentUserInformation方法是多余的,因为它只是服务调用的包装器。代码可以重构为:
ngAfterViewInit() {
this.loginService.GetCurrentUserData().subscribe(data => {
this.responseData = data;
if (this.responseData.code != responseCodes.success) {
this.googleInit();
}
});
}
Run Code Online (Sandbox Code Playgroud)
为了确保在处理响应之前执行异步调用,您可以使用 ReactiveX 中的 Observable.forkJoin() 。
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
Run Code Online (Sandbox Code Playgroud)
Observable.forkJoin(
this.http.get('/links.json').map((response:Response) => response.json()),
this.http.get('/bookmarks.json').map((response:Response) => response.json())
).subscribe(
data => {
this.links = data[0]
this.bookmarks = data[1]
},
error => console.error(error)
);
Run Code Online (Sandbox Code Playgroud)
subscribe() 函数的 onNext 处理程序将在所有 HTTP 请求成功完成时执行。
| 归档时间: |
|
| 查看次数: |
44452 次 |
| 最近记录: |