你好社区,
我正在尝试使用 HttpClient 模块从我的 api 获取一些数据。
api 调用是在我的服务中定义的。我在组件中的 Lifecyclehooks 中调用它们,但我很难理解返回的可观察量的行为以及如何在 ngOnInit 中获取它的值。
我构建了一个示例代码,用于记录返回的数据对象以了解它们的行为。服务函数返回可观察值。
这就是我的示例代码的样子:
我的样本服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ConfigService } from '../config/config.service';
@Injectable( {
providedIn: 'root'
} )
export class ExperimentalService {
constructor(private http: HttpClient, private ConfigService: ConfigService) {}
private _apiRootUrl: string = this.ConfigService.get('api_root_url');
private _apiUser: string = this.ConfigService.get('api_user');
private _apiPath: string = this.ConfigService.get('api_path');
public getLights() {
return this.http.get(
`${this._apiRootUrl}/${this._apiUser}/${this._apiPath}`
);
}
}
我的示例组件:
import { Component } from '@angular/core';
import { ExperimentalService } from '../../services/experimental/experimental.service';
@Component({
selector: 'app-experimental',
templateUrl: './experimental.component.html',
styleUrls: ['./experimental.component.scss']
})
export class ExperimentalComponent {
constructor(private ExperimentalService: ExperimentalService) { }
private test1;
private test2;
private executed: boolean = false;
ngOnInit(): void {
console.log("----- ngOnInit -----");
this.ExperimentalService.getLights().subscribe(
(data) => {
this.test1 = data;
console.log("Test: 1.1", this.test1); // --- 1.1 ---
}
);
console.log("Test: 1.2", this.test1); // --- 1.2 ---
}
ngDoCheck(): void {
console.log("----- ngDoCheck -----");
if (this.executed === false) { // if: only to avoid endless loop
this.ExperimentalService.getLights().subscribe(
(data) => {
this.test2 = data;
console.log("Test: 2.1", this.test2); // --- 2.1 ---
}
);
console.log("Test: 2.2", this.test2); // --- 2.2 ---
console.log("Test: 1.3", this.test1); //to check if test1 is coming after ngOnInit
if (this.test2) {
this.executed = true;
}
}
}
}
控制台输出:
----- ngOnInit -----
Test: 1.2 undefined
----- ngDoCheck -----
Test: 2.2 undefined
Test: 1.3 undefined
----- ngDoCheck -----
Test: 2.2 undefined
Test: 1.3 undefined
Test: 1.1 Object { 1: {…}, 2: {…}, 3: {…} }
----- ngDoCheck -----
Test: 2.2 undefined
Test: 1.3 Object { 1: {…}, 2: {…}, 3: {…} }
Test: 2.1 Object { 1: {…}, 2: {…}, 3: {…} }
----- ngDoCheck -----
Test: 2.2 Object { 1: {…}, 2: {…}, 3: {…} }
Test: 1.3 Object { 1: {…}, 2: {…}, 3: {…} }
Test: 2.1 Object { 1: {…}, 2: {…}, 3: {…} }
- 为什么 .2 在 .1 之前被记录?
-
为什么第一个周期返回 undef?(我的想法:Api 响应时间太长?!)
-
如何获取 ngOnInit 中的值?如果我的想法 2. 是正确的,是否可以选择等待 api 响应?
谢谢你的每一个帮助!