Angular 使用wait-like进行角度订阅服务
我有Angular 使用wait-like进行角度订阅服务,angular,rxjs,Angular,Rxjs,我有这是service.service.ts @Injectable({ providedIn: 'root' }) export class ThisIsService { header = new HttpHeaders({ 'Authorization': TOKEN, 'Content-Type': 'application/json' }); constructor( private http: HttpC
这是service.service.ts
@Injectable({
providedIn: 'root'
})
export class ThisIsService {
header = new HttpHeaders({
'Authorization': TOKEN,
'Content-Type': 'application/json'
});
constructor(
private http: HttpClient
) { }
getFunction() {
return this.http.get(API_URL , { headers: this.header })
.pipe(
catchError(err => this.handleError(err))
);
}
private handleError(error: HttpErrorResponse) {
return throwError(error);
}
}
variable: any;
constructor(
private serviceService: ThisIsService
) { }
ngOnInit() {
this.serviceService.getFunction().subscribe(
(resp) => {
if (resp['success'])
this.variable = resp['data'];
}
);
console.log(this.variable);
}
在mycomponent.ts中
@Injectable({
providedIn: 'root'
})
export class ThisIsService {
header = new HttpHeaders({
'Authorization': TOKEN,
'Content-Type': 'application/json'
});
constructor(
private http: HttpClient
) { }
getFunction() {
return this.http.get(API_URL , { headers: this.header })
.pipe(
catchError(err => this.handleError(err))
);
}
private handleError(error: HttpErrorResponse) {
return throwError(error);
}
}
variable: any;
constructor(
private serviceService: ThisIsService
) { }
ngOnInit() {
this.serviceService.getFunction().subscribe(
(resp) => {
if (resp['success'])
this.variable = resp['data'];
}
);
console.log(this.variable);
}
问题是console。现在调用log
时没有完成服务,结果打印了变量的值=未定义的
在这种设置中,我将如何使用wait
(或任何替代方法)
我希望服务先完成,然后再继续下一个功能。谢谢,Async/Await与promission一起使用,所以您需要首先将其转换为promise,然后使用Await关键字。可能有不同的方法可以做到这一点,但我会保持使用简单:
ariable: any;
constructor(
private serviceService: ThisIsService
) { }
ngOnInit() {
this.getData();
}
async getData() {
try {
const resp = await this.serviceService.getFunction().toPromise();
console.log(resp);
} catch(e) {
console.log(`Error: ${e}`);
}
console.log(this.variable);
}
您可以使用rxjs的.toPromise方法或定义subscriptionresp中的所有操作现在变成ZoneAwarePromise
:结构变成:\uuuuuuuuu zone\uSymbol\uuuuu值:{/*我从服务检索的数据*/}
当我添加此.variable=resp.\uuuuuu zone\uSymbol\uuu值时,值就是[]
。如何将resp
添加到此.variable
中?这是打字错误,我添加了正确的一个。请检查一下这个。你也可以在resp上使用then,所以我想你可以添加它。无论承诺何时解决,您都可以获得价值观。但是async/await更好,我添加了相同的代码。