在Angular中,当使用HTTP GET请求时,可以通过订阅Observable来获取返回的数据。以下是一个示例,展示了如何解决返回undefined的问题:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
// ...
})
export class AppModule { }
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
this.http.get('https://api.example.com/data')
.subscribe(response => {
console.log(response); // 输出返回的数据
});
在这个示例中,我们发送了一个GET请求到https://api.example.com/data,并使用subscribe方法来订阅Observable。在订阅中,我们可以处理返回的数据,这里将其打印到控制台上。
通过以上步骤,你应该能够正确地获取到返回的数据,而不是undefined。确保URL是有效的,并且服务器返回了正确的数据。如果仍然遇到问题,可以检查网络请求的返回状态,查看是否有其他错误发生。