要将HttpResponse
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class DataService {
constructor(private http: HttpClient) {}
getData(): Observable {
return this.http.get>('your_api_url').pipe(
map(response => {
// 在这里进行转换
let myClass: MyClass = new MyClass();
myClass.property1 = response.body.property1;
myClass.property2 = response.body.property2;
// 更多属性转换...
return myClass;
})
);
}
}
class MyClass {
property1: string;
property2: number;
}
在上面的示例中,我们使用HttpClient
发送HTTP GET请求并指定响应类型为HttpResponse
。然后,使用map
运算符将响应转换为MyClass
类的实例。在map
函数中,我们可以访问response.body
属性来获取实际的响应数据,并将其转换为目标类的实例。最后,返回转换后的类实例的Observable。
请根据你的实际需求修改代码中的URL和属性转换逻辑。