Angular 6无法将HttpResonse <any>转换为类

时间:2018-10-19 15:31:52

标签: angular6

我对角度6很陌生。 下面的代码在以前的版本中可以正常工作,但是一旦转换为HttpClient-> HttpResponse,它就会失败。

getTeamMembers(): Observable<TeamMembers[]> {
    const url = `${this.baseUrl}/workusers`;
    return this.authService.AuthGet(url)
        .map(this.extractData)
        .catch(this.handleError);
}

public extractData(response: HttpResponse<any>) {
    const body = response.json();
    return body || {};
}

当我尝试在我获得的extractData()中尝试response.json()时,类型HttpResonse错误中不存在属性json()。

typeof(response)作为对象给出

这是我的AuthGet方法:

AuthGet(url: string, options?: { observe: 'response' }): Observable<HttpResponse<any>> {
    if (options) {
        options = this._setRequestOptions(options);
    } else {
        options = this._setRequestOptions();
    }
    return this.http.get(url, options);
}

有人可以帮我在这里做什么错吗?

谢谢

1 个答案:

答案 0 :(得分:0)

HttpClient已经返回JSON,这与Http的早期版本不同,在该版本中您必须明确要求它。

这里是获取结果并映射到类的一种方法:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

class Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
  constructor(raw: any) {
    Object.assign(this, raw);
  }
};

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers: [HttpClient]
})
export class AppComponent implements OnInit  {
  todo: Todo;
  constructor(private http: HttpClient) {}
  ngOnInit() {
    // Tell Typescript the result of this will be of type Todo
    this.http.get<Todo>('https://jsonplaceholder.typicode.com/todos/1')
      .pipe(
        // Create a new class based on the result JSON
        map((data: Todo) => new Todo(data))
      )
      .subscribe((data: Todo) => {
        this.todo = data;
        console.log(this)
      })
  }  
}

Stackblitz