gpt4 book ai didi

angular - 处理数据检索延迟 Angular

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:24:29 25 4
gpt4 key购买 nike

首先,十多年来没有编码(前 Java 开发人员),所以只是将熟悉 Angular 4 作为一种爱好,但我缺乏基本的了解。我搜索了使用可观察对象处理数据检索延迟,但没有返回任何相关结果。希望这里有人可以帮助和解释。它围绕以下 TypeScript 代码展开(也请参见内联注释):

远程数据服务

export class RemoteDataService {
private headers = new Headers({ 'Content-Type': 'application/json' });
constructor(private http: Http) { }

public getData(url) {
return this.http.get(url)
.map(
(response: Response) => {
const data = response.json();
return data;
}
)
}
}

文章服务

export class ArticleService implements OnInit {
_articles: Article[];

constructor(private _remoteDataService: RemoteDataService) {
this.onGet();
console.log(JSON.stringify(this._articles)) **//<- this._articles is null**
setTimeout(()=> console.log(JSON.stringify(this._articles + "////")), 3000)
} **//<- but if I wait 3 seconds this._articles is set to data elements**

public onGet() {
this._remoteDataService.getData('./assets/articles.json')
.subscribe(
(articles: any[]) => {
this._articles = articles,
console.log(this._articles) **//<- this_.articles is set**
},
(error) => console.log(error))

//console.log(this._articles) **//<- if I uncomment this_.articles is null, huh?**
}
}

输出:

article.service.ts:34 "undefined////"

article.service.ts:46 (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, ?>{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

article.service.ts:35 "[object Object],[object Object],[object Object],[object >Object],[object Object],[object Object],[object Object],[object Object],[object >Object],[object Object],[object Object],[object Object],[object Object],[object >Object],[object Object],[object Object],[object Object],[object Object],[object >Object],[object Object]////"

我的问题是:

1) 为什么在 onGet() 方法中 this._articles 从设置为 null 开始?

2) 数据延迟通常如何处理,因为我调用服务的组件因为文章尚未设置而崩溃?

最佳答案

1) 您对服务的调用是异步,这意味着调用是在另一个线程中进行的,但是onGet() 继续执行。当您在控制台中登录时,this._articles 尚未设置。

2) 哇,这是个大问题,答案很大程度上取决于您要完成的任务。一方面,使用 setTimeout() 是不好的做法。您需要以无需任何数据即可工作的方式设计您的组件。如果是您的模板损坏了,safe navigation operator可能会派上用场。如果您提供更多详细信息,我很乐意提供帮助。

关于angular - 处理数据检索延迟 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45849685/

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