在这里我知道如何从json中获取数据,但是我发现很难同时从基于引用另一个json的id的json形式获取数据,问题陈述在这里,我有一个api / users的json,包含10个用户,每个都有10个博客,还有一个api / posts api,其中包含所有帖子,现在我必须检索数据,例如当我单击user1时,必须显示与userid 1相关的博客
这是service.ts
getUsers(): Observable<UserModel[]> {
return this.http.get<UserModel[]>(`${this._url}/users`)}
getUserBlogPosts(userId:number){
return this.http.get<BlogsModel[]>(`${this._url}/posts?userId=${userId}`)}
user.ts
ngOnInit() {
this.getUsersOnSubscribe() }
getUsersOnSubscribe(){
this.service.getUsers().subscribe(
data =>{
console.log(data);
this.users = data;
}
)}
onClickUser(users){
this.currentUser = users
let id = users.id
console.log(id)
this.service.getUserBlogPosts(id).subscribe(
data=>{
console.log(data)
this.currentUser = data
}) }
.blog.ts
ngOnInit() {
this.getBlogsList(); }
getBlogsList() {
let id = this.blog
this.service.getUserBlogPosts(id.userId).subscribe(
data=>{
console.log(data)
this.blogs=data;
}
)}
}
当我在控制台中单击onclick(users)时,我能够在用户组件中过滤数据,我希望此输出在blogs组件中显示如何执行此操作,并且在获得user1的blog之后也遇到了问题在单击它重定向到url / posts?userId = 1,当我尝试将url编辑为url / posts?userId = 2时,它没有显示任何数据。如何解决这个问题
答案 0 :(得分:0)
在您的情况下,您可以重用服务并从behaviorSubject发出数据
Service.ts
constructor() {
this._currentUser = new BehaviorSubject(null);
this.currentUser$ = this._currentUser.asObservable();
}
setCurrentUser(user) {
this._currentUser.next(user);
}
user.ts
this.service.getUserBlogPosts(id).subscribe(
data=>{
this.currentUser = data
// Emits your value
this.service.setCurrentUser(this.currentUser)
}
)
blog.ts
this.service.currentUser.subscribe(
user => {
//The data you emitted from user.ts is available here, do your logic
}
)