gpt4 book ai didi

javascript - 无法将订阅的可观察对象作为字符串放入集合中

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

我是 typescript 和 javascript 的新手,我真的很难搞清楚集合和文件 io 是如何工作的。我正在尝试从 json 文件中获取数据,尽管当我将其放入集合中时该集合没有数据,但我成功了。

代码如下:

在我的服务类中:

  private configuration = "../../assets/Configurations/testConfiguration.json";

constructor(private http: HttpClient) {}

getBlogs(blog: string): Observable<IBlogPost[]> {
return this.http.get<IBlogPost[]>(blog);
}

getConfigurations() {
var configurationsData = [];
this.http.get(this.configuration).subscribe(data => {
configurationsData.push(data);
console.log(data);
// This will work and will print all the paths
});

//This will not work and will not print them, like if the collection is empty
configurationsData.forEach(x => console.log(x));

return configurationsData;
}

我在哪里注入(inject)我的服务类:

blogs: IBlogPost[] = [];

private blogsPaths: string[] = [];

errorMessage = "";

constructor(private appUtilityService: AppUtilityServices) {}

ngOnInit() {
//This will not work, blogsPaths will not received the full collection as it should
this.blogsPaths = this.appUtilityService.getConfigurations();



this.blogsPaths.forEach(blogPath =>
this.appUtilityService.getBlogs(blogPath).subscribe(
b =>
b.forEach(blog => {
this.blogs.push(blog);
}),
error => (this.errorMessage = <any>error)
)
);
}

测试配置.json:

[
"../../assets/BlogPosts/testBlog1.json",
"../../assets/BlogPosts/testBlog2.json"
]

如果你提供了一个关于集合如何在 javascript 中工作以及如何正确返回它们的好教程,则奖励

最佳答案

原来是这样,是真的……

这里我做得很好:

初始化:

this.appUtilityService.getConfigurations().subscribe(
b =>
b.forEach(x => {
this.appUtilityService.getBlogs(x).subscribe(
b =>
b.forEach(blog => {
this.blogs.push(blog);
}),
error => (this.errorMessage = <any>error)
);
}),
error => (this.errorMessage = <any>error)
);

应用程序服务:

  getBlogs(blog: string): Observable<IBlogPost[]> {
return this.http.get<IBlogPost[]>(blog);
}

getConfigurations(): Observable<string[]> {
return this.http.get<string[]>(this.configuration);
}

让它变得非常漂亮:

  ngOnInit() {
this.initializeBlog();
}

private initializeBlog(): void {
this.appUtilityService.getConfigurations().subscribe(
b =>
b.forEach(x => {
this.appUtilityService.getBlogs(x).subscribe(
b =>
b.forEach(blog => {
this.blogs.push(blog);
}),
error => (this.errorMessage = <any>error)
);
}),
error => (this.errorMessage = <any>error)
);
}

关于javascript - 无法将订阅的可观察对象作为字符串放入集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56825955/

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