gpt4 book ai didi

Angular 8 如何从 ngOnInit 中的可观察值中获取值(value)以及它们的行为方式

转载 作者:行者123 更新时间:2023-12-05 09:11:50 26 4
gpt4 key购买 nike

<分区>

你好社区
我正在尝试使用 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: {…} }


  1. 为什么 .2 在 .1 之前被记录?
  2. 为什么第一个周期返回 undef?(我的想法:Api 需要很长时间才能提供响应?!)
  3. 如何获取 ngOnInit 中的值?如果我的想法 2. 正确,是否可以选择等待 api 响应?


谢谢您的帮助!

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