gpt4 book ai didi

angular - 从 API 服务 Angular 4 获取数据

转载 作者:可可西里 更新时间:2023-11-01 17:05:30 26 4
gpt4 key购买 nike

我构建了一个服务,它从 API observable 获取特定 ID。如果我从服务类中获取 console.log(data),则该服务正在运行,但我无法在我的组件中获取数据。

See the console

服务:

getSpecificStory(storyId) {
return this.getToken()
.map(idToken => {
let headers = new Headers();
headers.set('user_token', idToken)
return this.http
.get(`${this.apiUrl}/stories/${storyId}`, { headers: headers })
.subscribe((res: Response) => {
const data = res.json();
console.log(data)
return data;
});
})
.catch(this.handleError);
}

组件:

export class StoryModalComponent implements OnInit {
story: any;
storyId: any;
hitsArray: Array<Object>;

constructor(private storiesService: StoriesService, private route: ActivatedRoute) {
}

ngOnInit() {
this.route.params
.subscribe(
params => {
this.storyId = params['storyId']
})
console.log(this.storyId)
this.getStoryObject();
}


getStoryObject() {
console.log(this.storyId)
this.storiesService.getSpecificStory(this.storyId)
.subscribe(
(data) => {
this.story = data;
console.log(this.story)
})
}
}

最佳答案

您正在寻找 flatMap 运算符而不是 map。

getSpecificStory(storyId) {
return this.getToken()
.flatMap(idToken => {
let headers = new Headers();
headers.set('user_token', idToken)
return this.http
.get(`${this.apiUrl}/stories/${storyId}`, { headers: headers })
});
})
}

.flatMap 期望您返回一个可观察对象(在您的例子中是 this.http.get(...))。现在 getSpecificStory 方法返回一个可观察对象。所以你订阅了你的组件

this.storiesService.getSpecificStory(this.storyId)
.subscribe(
(data) => {
this.story = data;
console.log(this.story)
})

当您链接依赖的可观察对象(您的 firebase getToken() 方法和您的 this.http.get())时,这是常用方法

关于angular - 从 API 服务 Angular 4 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46771002/

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