简体   繁体   English

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

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

I'm trying to send this POST to an API but seems impossible to access response data (which is coming as text and I need to 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)})
  );
}

I'm getting this error:我收到此错误:

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

Am I doing something wrong?难道我做错了什么?

If you just want to access the response data, you can use then() method.如果只想访问响应数据,可以使用 then() 方法。

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

Why are you mapping in your subscription? 为什么要在订阅中映射? All you need to do is display the data. 您需要做的就是显示数据。

Just do .subscribe(data => console.log(JSON.stringify(data)) get rid of the map. 只需执行.subscribe(data => console.log(JSON.stringify(data))摆脱地图。

Edit: Also your .subscribe needs to be outside your pipe, if you do need to pipe that it. 编辑:此外,如果您需要通过管道将.subscribe移到管道之外。 Which you don't in this instance. 在这种情况下,您不会这样做。

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

your subscribe method can't be place inside the pipe 您的订阅方法不能放在管道内

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

you don't need the return statement 您不需要return语句

the othe case is to return an observable from login method so in this case you can't subscribe inside the login method 其他情况是从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()))
}

use login method as observable 使用登录方法可观察

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

There are multiple issues with your implementation. 您的实现存在多个问题。

I've mentioned all the issues inline in code comments so that they're easy to follow: 我已经在代码注释中内联提到了所有问题,因此很容易理解:

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

As the response coming from server is of type text, have your tried explicitly specifying the response as text in the post request like below, 由于来自服务器的响应为文本类型,因此请尝试如下所示在发布请求中将响应明确指定为文本,

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

By default angular HttpClient tries to process the response as json and fails in parser when a text-based response is received, altough the http request succeeds 默认情况下,角度HttpClient尝试将响应处理为json并在收到基于文本的响应时在解析器中失败,尽管http请求成功

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

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