Angular 8 Asyn c вызов не ожидает выполнения обещания и приводит к неверному запросу - PullRequest
0 голосов
/ 15 февраля 2020

я хочу, чтобы мой вызов asyn c не вызывал go для следующих операторов до его завершения, но он все еще выполняется, а также после завершения запроса, он приводит к ошибке как неверный запрос, даже если URL-путь и заголовки http верны Если я делаю это, используя наблюдаемый и подписывающийся способ его работы, но переходя к следующим операторам перед завершением запроса, я подумал, что обещание async / await может помочь, но я делаю что-то не так, любая помощь очень важна. Вот мой код.

myapp.service.ts

//Because we are not using a type checker, so the response should be extracted. Add this function after the constructor for extract it.
private extractData(res: Response) {
    let body = res;
    return body || {};
  }
private handleError(error) {
    return throwError(error);
  }
async getEntityDependencies(entitytype: string) {
    try {      
      var authheader = { headers: new HttpHeaders({ 'accesstoken': this.accesstoken, 'Content-Type': 'application/json', })};

      return await this.http.get(this.endpoint, authheader).pipe(map(this.extractData), catchError(this.handleError)).toPromise();       
    } 
    catch (error) {
      console.log(error);
    }
  }

newform.component.ts

async CreateForm() {
  // const data = await this.rest.getEntityDependencies(this.dataservice.entitytype)
  await this.rest.getEntityDependencies(this.dataservice.entitytype).then((data: {}) => { // data is getting undefined since request results Bad request
    // my stuff using data...
  }, error => {
    console.log(error, "Error from API");
  });
}

1 Ответ

1 голос
/ 15 февраля 2020

в коде есть две проблемы

сначала вам не нужно return await

async getEntityDependencies(entitytype: string) {
    try {      
      var authheader = { headers: new HttpHeaders({ 'accesstoken': this.accesstoken, 'Content-Type': 'application/json', })};

      return this.http.get(this.endpoint, authheader)
         .pipe(
            map(this.extractData), 
            tap(data => console.log('data in service', data))
            catchError(this.handleError)
         ).toPromise();       
    } 
    catch (error) {
      console.log(error);
    }
  }

второй этот метод

async CreateForm() {
  try
  {
     const data = await this.rest.getEntityDependencies(this.dataservice.entitytype);
     console.log('data', data);
  }
  catch(ex) {
     console.error(ex);
  }
}
...