简体   繁体   English

Angular 5 Http api请求在chrome dev工具中得到响应,但不会返回

[英]Angular 5 Http api request gets response in chrome dev tools but won't return

I have a "Response" content : 我有一个“回复”内容:

在此输入图像描述

But I can't console.log it. 但我不能控制它.log它。

Update (15:00 22/03/2018, this is new version) : 更新(15:00 22/03/2018,这是新版本):

in actions.component.ts : 在actions.component.ts中:

 generatePOR(){
    this._api.exportToERP(this.selection).subscribe((res) => {
      console.log('heelo I am second phase');
      console.log(res);
    }, (error) => console.log(error), () => {});
  }

in api.ts : 在api.ts:

generatePOR (idList): any {
  const apiURL = `${this.API_URL}/purchaseorders/generatePOR`;
  return this._http.post(apiURL, idList, { headers: new HttpHeaders().set('Content-Type', 'application/json') });
}

here is is the console log : 这是控制台日志:

ro {headers: Ge, status: 200, statusText: "OK", url: "http://localhost:8080/purchaseorders/generatePOR", ok: false, …}error: {error: SyntaxError: Unexpected token P in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttp…, text: "PARTNER_RELATION_CUSTOMER_GROUPCODE;PARTNER_RELATI…95;2;NEW ORDER PUBLISHED;;;2017-10-289 08:00:00
↵"}headers: Ge {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}message: "Http failure during parsing for http://localhost:8080/purchaseorders/generatePOR"name: "HttpErrorResponse"ok: falsestatus: 200statusText: "OK"url: "http://localhost:8080/purchaseorders/generatePOR"__proto__: eo

Update (16:31) : 更新(16:31):

generatePOR (idList): any {
    const apiURL = `${this.API_URL}/purchaseorders/generatePOR`;
    this.PORresult = this._http.post(apiURL, idList, {
      observe: 'response',
      headers: new HttpHeaders({'Content-Type': 'application/json'}),
      responseType: 'text' as 'text'
    })
      .map((res, i) => {
        console.log('hi');
        console.log(res);
      });
    return this.PORresult;
  }

output : 输出:

hi  
ao {headers: Ge, status: 200, statusText: "OK", url: "http://localhost:8080/purchaseorders/generatePOR", ok: true, …}body: "PARTNER_RELATION_CUSTOMER_GROUPCODE;PARTNER_RELATION_CUSTOMER_PLANTCODE;PO_UpdateVersion;PARTNER_RELATION_SUPPLIER_NOLOCAL;PO_PoNumber;PO_PosNumber;PO_RequestNumber;PARTNER_RELATION_SUPPLIER_NO;PO_CollabPrice;PO_CollabPromQty;PO_Status;PO_SupAckNumber;PO_CollabComment;PO_CollabPromDate
↵PARTNER_RELATION_CUSTOMER_GROUPCODE;PARTNER_RELATION_CUSTOMER_PLANTCODE;1;PARTNER_RELATION_SUPPLIER_NOLOCAL;4500634818;00070;0001;PARTNER_RELATION_SUPPLIER_NO;464.95;2;NEW ORDER PUBLISHED;;;2017-10-289 08:00:00
↵"headers: Ge {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}ok: truestatus: 200statusText: "OK"type: 4url: "http://localhost:8080/purchaseorders/generatePOR"__proto__: eo

heelo I am second phase  undefined

use .body to get the body of your response 使用.body来获取你的回复

if (res) {
      if (res.status === 201) {
        return [{ status: res.status, json: res.body }]
      }
      else if (res.status === 200) {
        console.log('hello, I am a result ',res);
        return [{ status: res.status, json: res.body }]
      }
    }

The way you are returning promise is wrong here. 你回归承诺的方式在这里是错误的。

generatePOR (idList): Observable<any> {
const apiURL = `${this.API_URL}/purchaseorders/generatePOR`;
return this._http.post(apiURL, idList, { observe: 'response' }, )
  .map((res: HttpResponse<any>, i) => {
    if (res) {
      if (res.status === 201) {
        return [{ status: res.status, json: res }]
      }
      else if (res.status === 200) {
        console.log('hello, I am a result ',res);
        return [{ status: res.status, json: res }]
      }
    }
  })
  .catch((error: any) => {
    if (error.status < 400 ||  error.status ===500) {
      return Observable.throw(new Error(error.status));
    }
  })
  .pipe(
    catchError(this.handleError)
  );

} }

don't return this.results, return the the promise directly . 不要退货。结果,直接退还承诺。 Because api may take time. 因为api可能需要时间。 But before that you are returning the results object. 但在此之前,您将返回结果对象。 That is the reason you are not getting that data. 这就是你没有得到这些数据的原因。

After a day and a half of toiling here's what worked for me : 经过一天半的劳动,这对我有用:

actions.component.ts : actions.component.ts:

generatePOR(){
  this._api.generatePOR(this.selection).subscribe(res => {
    if(res !== null && res !== undefined){
      console.log(res.body);
    }
  }, (error) => console.log(error), () => {});
}

api.ts : api.ts:

generatePOR(idList): any {
  const apiURL = `${this.API_URL}/purchaseorders/generatePOR`;
  this.PORresult = this._http.post(apiURL, idList, {
    observe: 'response',
    headers: new HttpHeaders({'Content-Type': 'application/json'}),
    responseType: 'text' as 'text'
  }).catch(this.handleError);
  return this.PORresult;
}

...and making sure the backends send an actual file in the text/csv format and not just brute html . ...并确保后端以text/csv格式发送实际文件,而不仅仅是粗暴的html

this github thread helped alot in the creation of correct header and options : https://github.com/angular/angular/issues/18586 这个github线程帮助创建了正确的标题和选项: https//github.com/angular/angular/issues/18586

note: you must make both inline to the api call you cannot declare them as variables beforehand in the function or elsewhere in the class or application. 注意:你必须同时对api调用进行内联,你不能事先在函数中或类或应用程序的其他地方将它们声明为变量。 also the nonsensical parsing : responseType: 'text' as 'text' is a big key factor in making it work. 还有无意义的解析: responseType: 'text' as 'text'是使其工作的一个关键因素。

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

相关问题 在Chrome开发工具中调试导入的Angular库 - Debugging imported Angular library in chrome dev tools Angular CLI 的“ng serve”在 chrome 开发工具中出现错误时不引用打字稿源 - Angular CLI's "ng serve" doesn't refer to typescript sources upon errors in chrome dev tools Angular HTTP请求在Chrome中返回null,但在Firefox中有效 - Angular http request return null in chrome but works in firefox 如何使用 Angular 9 http post 请求从 API 获得响应 - How to get response from API using Angular 9 http post request 本地主机api请求的HTTP失败响应:0未知错误-Angular - Http failure response for localhost api request: 0 Unknown Error - Angular Chrome 开发工具可以帮助找出 Angular 组件名称吗? - Can Chrome Dev tools help figure out Angular component name? 如何在Chrome开发工具中获取地图角度CLI css文件? - How to Source Map Angular CLI css files in Chrome Dev Tools? Angular 2:无法访问http请求中的响应标头 - Angular 2: Can't access response headers in a http request Angular - 接收和返回 Observable<T> Http.post 中的响应 - Angular - receive and return Observable<T> response in Http.post Angular 应用程序在将一个视图导航到另一个视图时冻结,并且具有 HTTP 请求的高负载响应 - Angular App gets freeze when navigating one view to another with high payload response of HTTP Request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM