Angular 如何按顺序运行异步函数?
我有以下两项服务和职能: 第一个Angular 如何按顺序运行异步函数?,angular,http,asynchronous,Angular,Http,Asynchronous,我有以下两项服务和职能: 第一个 getData() { return this.http.post(this.base_URL + "web_app/login/", JSON.stringify(this.login)) .subscribe(response=>{ this.access_token = response['access_token']; console.log("received token " + this.access_token
getData() {
return this.http.post(this.base_URL + "web_app/login/", JSON.stringify(this.login))
.subscribe(response=>{
this.access_token = response['access_token'];
console.log("received token " + this.access_token)
localStorage.setItem( 'access_token', this.access_token );
this.access_token = localStorage.getItem('access_token');
console.log("set cookie value" + this.access_token);
}
第二个
farmAccess(){
let headers = new HttpHeaders();
this.access_token = localStorage.getItem('access_token');
headers.append('access_token', this.access_token);
console.log("retrieved cookie value" + this.access_token);
return this.http.get(this.baseURL + 'web_app/farm_access/', {headers})
.subscribe(res => console.log(res),)};
我希望按此顺序运行它们,因为我需要登录调用的结果来进行farmAccess调用
ngOnInit(): void{
this.data = this.login.getData();
this.farmAccessdata = this.getFarmAccess.farmAccess();
}
我该怎么做?谢谢 不要订阅,而是从
getData()
映射响应
并在组件文件中订阅getData()
。异步数据返回后,可以调用farmAccess()
当我将第一位放入getData函数时,它不允许我使用map函数?表示找不到名称“map”。我已经将'import'rxjs/add/operator/map'导入到文件中,因为这个
import{map}来自'rxjs/operators'
getData() {
return this.http.post(this.base_URL + "web_app/login/", JSON.stringify(this.login))
.pipe(map((response) => {
this.access_token = response['access_token'];
console.log("received token " + this.access_token)
localStorage.setItem( 'access_token', this.access_token );
this.access_token = localStorage.getItem('access_token');
console.log("set cookie value" + this.access_token);
}
));
}
ngOnInit(): void{
this.login.getData().subscribe((data) => {
this.data = data;
this.farmAccessdata = this.getFarmAccess.farmAccess();
});
}