问题描述: 在Angular 6中,当进行HTTP GET请求时,返回的对象是undefined。
解决方法: 有几种可能的原因导致返回的对象为undefined,下面给出两个常见的解决方法。
示例代码:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('http://example.com/api/data')
.subscribe(response => {
console.log(response); // 在这里打印响应对象
});
}
}
在上述示例代码中,使用箭头函数来定义subscribe的回调函数,确保上下文指向DataService类。
示例代码:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('http://example.com/api/data')
.pipe(
map(response => {
console.log(response); // 在这里打印响应对象
return response; // 返回响应对象
})
);
}
}
在上述示例代码中,使用map运算符对响应进行处理,并返回响应对象。
这些解决方法都可以确保正确地获取到HTTP GET请求的响应对象。根据具体的业务逻辑,你可以选择其中一种或者结合使用。