gpt4 book ai didi

Angular5 HttpClient,在GET api调用后设置变量

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:21 24 4
gpt4 key购买 nike

我有多个组件使用的服务(我们称它为 MySharedService)。在 MySharedService 中,我调用了另一个进行 API 调用的服务。 MySharedService 包含在我的 GET 调用之后分配的 JavaScript 对象。

我的问题是我的组件依赖于 JavaScript 对象在它们的构造函数中设置它们的值。当 JavaScript 可能由于 API 调用尚未完成而未定义时,我如何设置它们的值?这是一个示例:

API服务

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
/* Other imports */

@Injectable()
export class ApiService {

constructor(private http: HttpClient) { }

getTestData(): Observable<MyDataInterface> {
const API_URL = 'some_url_here';
return this.http.get<MyDataInterface>(API_URL, { observe: 'response' });
}
}

我的共享服务

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
/* Other imports */

@Injectable()
export class MySharedService {

myData: MyDataInterface;

constructor(private apiServie: ApiService) {
this.apiService.getTestData().subscribe((response) => {
this.myData = { ...response.body };
console.log(this.myData);
});
}
}

测试组件

import { Component, OnInit } from '@angular/core';
import { MySharedService } from '../../../services/myshared.service';
/* Other imports */

@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

name: string;
/* Other variables here. */

constructor(private mySharedService: MySharedService) {
// Error here because myData has not been populated, yet.
this.name = this.mySharedService.myData.name;
}
}

因此,当我尝试从 myData 对象访问数据时,问题发生在我的组件内部,因为它还没有被填充(console.log()最终会在几秒钟后打印出数据)。我应该如何获取这些值?我只想调用一次其余服务并将对象保存在 MySharedService 中,然后让我的所有组件都使用该对象。

最佳答案

你应该使用 BehaviorSubject

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
/* Other imports */

@Injectable()
export class MySharedService {

myData: BehaviorSubject<MyDataInterface> = new BehaviorSubject(null);

constructor(private apiServie: ApiService) {
this.apiService.getTestData().subscribe((response) => {
this.myData.next({ ...response.body });
console.log(this.myData.getValue());
});
}
}

在组件构造函数中进行订阅是一种不好的做法,请改用 ngOnInit 生命周期 Hook 。

export class TestComponent implements OnInit {

name: string;
/* Other variables here. */

constructor(private mySharedService: MySharedService) {
}

ngOnInit() {
this.mySharedService.myData.subscribe((data: MyDataInterface) => {
if (data)
this.name = data.name;
});
}
}

网络调用将只进行一次,数据将缓存在 BehaviorSubject 中,所有组件都将订阅该对象。

现在为什么要使用 BehaviorSubject 而不是 Observable?因为,

  • 订阅 BehaviorSubject 后返回最后一个值,而常规可观察对象仅在收到 onnext 时触发。

  • 如果你想在不可观察的代码(没有订阅)中检索 BehaviorSubject 的最后一个值,你可以使用 getValue()方法。

关于Angular5 HttpClient,在GET api调用后设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50141552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com