繁体   English   中英

angular - 如何访问http post响应并解析为json?

[英]angular - how to access http post response and parse as json?

我正在尝试将此 POST 发送到 API,但似乎无法访问响应数据(它以文本形式出现,我需要解析为 JSON)。

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { tap } from 'rxjs/operators';
import { Storage } from '@ionic/storage';
import { EnvService } from './env.service';
import { Injectable } from '@angular/core';
import { map } from "rxjs/operators";

...

login(email: String, password: String) {

  let headers = new HttpHeaders({
    'Accept'       :'*/*',
    'Content-Type' :'text/plain'
  });

  let formData = {
    user       : 'myuser',
    pass       : 'mypass',
    retsession : true
  }

  return this.http.post(this.env.API_URL+'/login', JSON.stringify(formData), {headers:headers}).pipe(
    map((res:Response) => (res.text()))
    .subscribe(data => {console.log(data)})
  );
}

我收到此错误:

[ng] ERROR in src/app/services/auth.service.ts(42,8): error TS2339: Property 'subscribe' does not exist on type 'OperatorFunction<Response, Promise<string>>'.

难道我做错了什么?

如果只想访问响应数据,可以使用 then() 方法。

$http.post('yourURL', formData).then(function (response) {
    console.log("Response");
    console.log(response.data);
});

为什么要在订阅中映射? 您需要做的就是显示数据。

只需执行.subscribe(data => console.log(JSON.stringify(data))摆脱地图。

编辑:此外,如果您需要通过管道将.subscribe移到管道之外。 在这种情况下,您不会这样做。

return this.http.post(url, JSON.stringify(formData), {headers:headers}).pipe(
    map((res:Response) => (res.text()))).subscribe(data => {console.log(data)}
  );

您的订阅方法不能放在管道内

login(email: String, password: String) : void {

 ....

 this.http.post(this.env.API_URL+'/login', JSON.stringify(formData), {headers:headers})
  .pipe(map((res:Response) => (res.text())))
  .subscribe(data => {console.log(data)});
}

您不需要return语句

其他情况是从login方法返回一个observable,因此在这种情况下,您将无法在login方法中进行订阅

login(email: String, password: String) : Observable<any> {

 ....

 return this.http.post(this.env.API_URL+'/login', JSON.stringify(formData), {headers:headers})
  .pipe(map((res:Response) => (res.text()))
}

使用登录方法可观察

  login('example@example.com','123456').subscribe(data => {console.log(data)});

您的实现存在多个问题。

我已经在代码注释中内联提到了所有问题,因此很容易理解:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { tap } from 'rxjs/operators';
import { Storage } from '@ionic/storage';
import { EnvService } from './env.service';
import { Injectable } from '@angular/core';
import { map } from "rxjs/operators";

...

login(email: String, password: String) {

  // Issue 1: These headers need not be set explicitly. HttpClient automatically does that for you. So you can get rid of these.
  //let headers = new HttpHeaders({
  //  'Accept': '*/*',
  //  'Content-Type': 'text/plain'
  //});

  let formData = {
    user: 'myuser',
    pass: 'mypass',
    retsession: true
  }

  // Issue 2: You're stringifying the request payload which is supposed to be sent as a JSON Object. So remove the JSON.stringify
  // Remove the headers too as we've gotten rid of them above.

  // Issue 3: I think in the pipe and map you're trying to call .json on the response. Since you're using HttpClient, that also isn't really required as HttpClient does that out of the box for you. So get rid of those.
  return this.http.post(this.env.API_URL + '/login', formData)
    .subscribe(data => console.log(data));
}

由于来自服务器的响应为文本类型,因此请尝试如下所示在发布请求中将响应明确指定为文本,

this.http.post(url, formData, {responseType: 'text' })

默认情况下,角度HttpClient尝试将响应处理为json并在收到基于文本的响应时在解析器中失败,尽管http请求成功

暂无
暂无

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

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