如何在Angular中按顺序运行异步函数?

时间:2018-06-15 14:49:24

标签: 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)
   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();
  }

我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:1)

而不是订阅,映射来自getData()的响应。

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);
              }
          ));
}

在您的组件文件中订阅getData()。返回异步数据后,您可以调用farmAccess()

ngOnInit(): void{

    this.login.getData().subscribe((data) => {
        this.data = data;
        this.farmAccessdata = this.getFarmAccess.farmAccess();
   });
}