我一直在重写Angular应用程序,该应用程序以前省略了http请求的使用。因此,服务组件中包含许多逻辑,并且通过使用以下格式的数组来模拟http请求:
[{"name": "somename1", "subset1": [
{"name": "somesubname1", "subset2": [
{"somemetric1": 0, "somemetric2: 1, "somemetric3": 2}]}]}]
这正是某些Web api(例如https:// localhost:5001 / api / values)上也显示的格式。
我的服务如下所示:
import { Injectable } from '@angular/core'
import { Subject, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class StrategyService{
data:any
constructor(private httpClient: HttpClient) {
}
getData() {
this.data = this.httpClient.get("https://localhost:5001/api/values")
}
如果我在例如getData()中使用console.log(this.data)并在运行我的应用程序时调用此函数,则控制台中将返回“ undefined”。当我将getData()的主体替换为
this.httpClient.get("https://localhost:5001/api/values").subscribe(data => {data = console.log(data)})
控制台会按所需格式返回数组(并显示在第一个块中)。实际上,控制台日志记录并不是我所需要的,因为我需要能够访问服务组件内部其他函数中的数据,这些函数需要特定于数组的方法,例如.find等。
我觉得这很简单,但是到目前为止我还没有成功。我试过了
import { Injectable } from '@angular/core'
import { Subject, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class StrategyService{
dat:any
constructor(private httpClient: HttpClient) {
}
getData() {
this.httpClient.get("https://localhost:5001/api/values").subscribe(data => {this.dat = data})
}
console.log(this.dat)仍返回“未定义”。
这是每个人都有异步代码的经典启动问题。研究rxjs +异步代码如何在Typescript中工作。
解决问题的方法是检查api响应返回后在subscribe
块中的数据。
this.httpClient.get("https://localhost:5001/api/values").subscribe(data => console.log(data))
public myFunction() {
this.httpClient.get("https://localhost:5001/api/values").subscribe(data => {
this.data = data;
console.log(this.data); // data is defined here
})
console.log(this.data); // data will be undefined here
}
指向有用资源的链接:
https : //www.learnrxjs.io/
https://angular.io/guide/http
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句