【发布时间】:2021-09-28 17:05:47
【问题描述】:
我正在尝试像这样在 Angular 中将数据从一个组件发送到另一个组件
onSubmit(form: NgForm){
this.newsService.searchNews(form.value.query).subscribe((res:any) => {
this.newsService.searchedNews.next(res.articles);
});
}
我正在将搜索到的新闻从我的搜索组件发送到我的主组件,如果我在我的主组件中订阅 ngOnInit 中的主题,则数据将为 null,因为尚未调用该方法或用户没有搜索任何东西,所以我的问题是,有没有办法在我的HomeComponent 中调用或执行此方法(SearchComponent)时,这就是服务
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { Article } from '../models/article';
@Injectable({
providedIn: 'root'
})
export class NewsService {
searchedNews = new BehaviorSubject<any>('');
constructor(private http: HttpClient) { }
getHeadlines() {
return this.http.get(`https://newsapi.org/v2/top-headlines?country=us&apiKey=${this.newsApiKey}`);
}
searchNews(query: string) {
return this.http.get(`https://newsapi.org/v2/everything?q=${query}&apiKey=${this.newsApiKey}`)
}
}
【问题讨论】:
-
你的home组件和父子搜索组件有什么关系吗?
-
不,它们无关
-
你能再解释一下你的问题吗,你的意思是数据为空并且你已经在家庭组件中收听,那么你要求什么?
-
当然,一旦用户搜索任何内容,搜索的数据就会存储在我的搜索组件中,我如何在我的主组件中发送这些数据,我在考虑 ngOnint 但主组件之前已经呈现用户搜索任何东西,希望我足够清楚
-
你在使用行为主题吗?可以添加代码 sn -p 吗?
标签: angular typescript rxjs