简体   繁体   English

异步执行函数 angular

[英]Execute functions async angular

I have a problem with my service, I need to call the function to getToken () asynchronously so that it initializes the token and token_type variables, these are necessary to be able to make all the requests to the API我的服务有问题,我需要异步调用 function 到 getToken () 以便它初始化 token 和 token_type 变量,这些是能够向 API 发出所有请求所必需的

this is my service这是我的服务

  async ngOnInit(){
    await this.getToken();

  }
  token: string;
  tokenType: string;
  getQuery(query: string): Observable<any> {
    const url = `https://api.spotify.com/v1/${ query }`;
    let bearer = this.tokenType+' '+this.token;
    let headers = new HttpHeaders();
    headers = headers.set('Authorization', bearer);
    console.log(headers);
    return this._http.get(url, { headers });
  }  
  getNewReleases() : Observable<any>{  
    return this.getQuery('browse/new-releases?limit=20')
              .pipe( map( data => data['albums'].items ));   
  }
 
 async getToken(): Promise<any>{
    const clientSecret  = '764b7c0645b849fa10f50f2a3450028';
    const clientId = '567b16bdfd23413294483002be41bc0';
    const url = 'http://127.0.0.1:3000/spotify/';    
  let prom =  await this._http.get(url + `${clientId}/${clientSecret}`).toPromise().then((data:any)=>{
    this.token = data.access_token;
    this.tokenType = data.token_type;
  })
  }
}

this is my component这是我的组件

 async   ngOnInit() {
await this.spotifyService.getNewReleases().subscribe((data:any)=>{
    console.log("comp"+data);      
    this.newSongs= data;
    this.loading=false;
  },(err:any)=>{
    console.log("error component");
    this.error=true;
    this.loading=false;
    this.errorMsg = err.error.error.message;
  });  
  }
}

there a many possible solutions.有很多可能的解决方案。 the simplest one would be to remove await this.getToken();最简单的方法是删除await this.getToken(); from the ngOnInit and add the following从 ngOnInit 并添加以下内容

getQuery(query: string): Observable<any> {
    ...
    if (this.token == null) {
        await this.getToken();
    }
    ....
  }  

My problem was more theory, then read this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function and understand my problem I solved this like this:我的问题更多的是理论,然后阅读这个链接https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function并理解我的问题我这样解决了这个问题:

service服务

 token: string;
  tokenType: string;
 async  getQuery2(query: string): Promise<Observable<any>> {

   if(!this.token){
     await this.getToken()
     .then((data: any ) => {
       console.log("ASYNQUERY DATA",{data});
       this.token = data.access_token;
       console.log("ASYNQUERY TOKEN "+this.token);
      this.tokenType = data.token_type;
      
        });
    }
    const url = `https://api.spotify.com/v1/${ query }`;
    let headers = new HttpHeaders();
    headers = headers.append('Authorization', 'Bearer '+this.token);
    console.log("HEADERS",headers);
    return this._http.get(url, { headers });
  }
   async getNewReleases() {
  return  await this.getQuery2('browse/new-releases?limit=20')
  .then((obs : Observable<any>) =>{
      console.log("NEW REALESES", obs);
      return obs.pipe(
        map( data => data['albums'].items )
      );
    }).catch(()=>{
      this.token= null;
      this.getNewReleases();
    });
  }
 async getToken(): Promise<any>{
    const clientSecret  = '764b7c0645b849a10f50f2a3450028';
    const clientId = '567b16bdfd2342942483002be41bc0';
    const url = 'http://127.0.0.1:3000/spotify/';    
    return await this._http.get(url + `${clientId}/${clientSecret}`).toPromise();
  }

component.ts组件.ts

async ngOnInit() {
  this.error=false;
  this.loading =true;

  // await this.spotifyService.getNewReleases();
  await this.spotifyService.getNewReleases().then((d:Observable<any>)=>{
    console.log("COMOPONENT",d);
    d.subscribe(data=>{
          this.newSongs= data;
    this.loading=false;
    },(err:any)=>{
          this.error=true;
    this.loading=false;
    this.errorMsg = err.error.error.message;
    });
  });

  
  }

however i don't like this code because is a lot but works... if anyone know a way of decrease that please tell me.但是我不喜欢这个代码,因为它很多但有效......如果有人知道减少的方法请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM