如何从httpclient angular 6访问响应值

时间:2018-07-06 09:49:43

标签: angular typescript angular6

我正在使用HttpClient发送请求。我已经提供了发送请求的服务。

com.xx.xx.test.xx.xx

在我的组件中:

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders,HttpResponse ,} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class HttpService {
  apiRoot: string = 'https://xxxx/api';

  constructor(private http: HttpClient) { }

  getQueryParam(obj) {
    let search = new HttpParams();
    for (let key in obj) {
      search =  search.set(key, obj[key]);
    }
    return search;
  }


  post(apiURL, params, data){
    console.log('Inside Post Request');
    let paramsData = this.getQueryParam(params);
      let CompleteURL = `${this.apiRoot}` + apiURL;
      return this.http.post(CompleteURL,data,{params : paramsData,observe : 'events'});
  }
}

在我的组件中,我想访问响应正文值,但是它给我错误:“类型'login() { this.admin.password = Md5.hashStr(<string>this.admin.password); this._httpService.post('/loginAdmin', { "name": "vinay" }, this.admin) .subscribe(res => { console.log(res.success); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { console.error('An error occurred:', err.error.message); } else { console.error(`Backend returned code ${err.status}, body was: ${err.error}`); } } ); } '上不存在属性'成功'。”我已经在Google上进行了一些界面检查。但是“ res.success”可以是数组或对象。 请帮助我。

1 个答案:

答案 0 :(得分:0)

login() {
    this.admin.password = Md5.hashStr(<string>this.admin.password);
    this._httpService.post('/loginAdmin', { "name": "vinay" }, this.admin)
      .subscribe(res:any => {
        console.log(res.success);

  },
    (err: HttpErrorResponse) => {
      if (err.error instanceof Error) {
        console.error('An error occurred:', err.error.message);
      } else {
        console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
      }
    }
  );
}

使用 任何 作为类型,以获取您从服务中获得的响应。希望有帮助:)