gpt4 book ai didi

javascript - 使用 Angular 从 API 访问数据(格式错误?)

转载 作者:行者123 更新时间:2023-11-30 20:15:55 25 4
gpt4 key购买 nike

我尝试从 API 访问的数据格式如下:

{
“array1”:[
{"id”:1, ”someProperty”:”A"},
{"id":2, "someProperty”:”B”}
],
“array2”:[
{"id”:1, ”anotherProperty”:”foo”, ”lastProperty”:”foo2”},
{"id":2, "anotherProperty”:”bar”, ”lastProperty”:”bar2”}
]
}

依赖类:

import { FirstArray } from './first-array';
import { SecondArray } from './second-array';
export class Dependencies {
constructor(
public array1: Array<FirstArray>,
public array2: Array<SecondArray>
) { }
}

FirstArray 类:

export class FirstArray {
constructor(
public id: number,
public someProperty: string
) { }
}

SecondArray 类:

export class SecondArray {
constructor(
public id: number,
public anotherProperty: string,
public lastProperty: string
) { }
}

我的 Dependencies service.ts 文件:

/** GET all Dependencies from the server */
getAllDependencies (): Observable<Dependencies[]> {
return this.http.get<Dependencies[]>(apiUrl).pipe(
tap(allDependencies => this.log('fetched allDependencies')),
catchError(this.handleError('getAllDependencies', []))
);
}

component.ts 文件:

ngOnInit() {
this.getAllDependencies();
console.log("allDependencies:",this.allDependencies);
}

allDependencies: Dependencies[];

getAllDependencies(): void {
this.DependenciesService.getAllDependencies()
.subscribe(allDependencies => this.allDependencies = allDependencies);
}

当我在组件文件中尝试 console.log(this.allDependencies) 时,结果未定义。数据从 API 中正确检索 - 'fetched allDependencies' 打印在日志中,我可以通过从服务文件中进行字符串化来在日志中打印 Dependencies 对象:

/** GET all Dependencies from the server */
getAllDependencies (): Observable<Dependencies[]> {
return this.http.get<Dependencies[]>(apiUrl).pipe(
tap(allDependencies => this.log(JSON.stringify(allDependencies))),
catchError(this.handleError('getAllDependencies', []))
);
}

我的问题:如何从我的组件文件中访问这些数据?我想我的数据结构中某处遗漏了一些东西,或者我遇到了与 Typescript 相关的错误,但我不确定。

最佳答案

您遇到的最大问题是,在您的组件中,调用服务的方法是 void并且不返回任何东西......

它并没有真正增加任何值(value),所以删除它并像这样访问数据:

ngOnInit() {
this.DependenciesService.getAllDependencies()
.subscribe(allDependencies => {
this.allDependencies = allDependencies;
console.log(this.allDependencies); // multi-line with log.
});
}

根据您的评论更新:

getAllDependencies(): void 更改您的方法至 getAllDependencies(): Observable<Dependencies[]>并在ngOnOnit内调用

getAllDependencies(): Observable<Dependencies[]> {
return this.DependenciesService.getAllDependencies();
}

ngOnInit() {
this.getAllDependencies().subscribe(.....);
}

关于javascript - 使用 Angular 从 API 访问数据(格式错误?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51919992/

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