【发布时间】:2020-07-01 20:53:08
【问题描述】:
我正在使用 Angular 9 来制作新闻应用程序。我正在使用 Times of India RSS Feed API https://timesofindia.indiatimes.com
这是我的 stackblitz 链接https://stackblitz.com/github/mehulk05/Newsapp
我的主组件中有类别,所以当我单击任何类别时,我会在我的服务中获取该类别的新闻并尝试在 NewsList 组件中显示它。但是当我更改我的类别时,我无法将最新数据从服务发送到 newsList 组件。虽然我在 NewsService 的控制台中获取更新的数据,但无法在 newsListComponent 中获取该数据
这是我的代码
Home.component.html
<div class="container mt-5">
<div class="col-xs-12">
<div class="row mt-4">
<div class="col-xs-3 col-md-3 sidelink">
<div class="list-group">
<a *ngFor="let c of categories"
class="list-group-item list-group-item-action"
id="list-home-list" [routerLink]=""
role="tab" aria-controls="home"
( (click)='onClick(c.url)'>{{c.type}}</a>
</div>
</div>
<div class="col-md-9 col-xs-9">
<router-outlet></router-outlet>
</div>
</div>
</div>
</div>
Home.component.ts
export class HomeComponent implements OnInit {
categories=[
{type:"home",url:"https://timesofindia.indiatimes.com/rssfeedstopstories.cms?feedtype=sjson"},
{type:"recent",url:"https://timesofindia.indiatimes.com/rssfeeds/1221656.cms?feedtype=sjson"},
{type:"india",url:"https://timesofindia.indiatimes.com/rssfeeds/-2128936835.cms?feedtype=sjson"},
{type:"cricket",url:"https://timesofindia.indiatimes.com/rssfeeds/4719161.cms?feedtype=sjson"}]
constructor(private ns:NewsserviceService,
private router:Router) { }
ngOnInit(): void {
}
onClick(title){
console.log(title)
this.ns.getUrl(title)
this.router.navigate(["/news-list"])
}
}
NewsService.ts
export class NewsserviceService {
url:string='https://timesofindia.indiatimes.com/rssfeedstopstories.cms?feedtype=sjson'
constructor(private http:HttpClient) {
}
getUrl(url){
this.url=url
this.getNewsList();
}
getNewsList(){
this.url='https://cors-anywhere.herokuapp.com/'+this.url
console.log(this.url)
this.http.get(this.url ).subscribe(data=>{
console.log(data)
})
}
}
NewsList.component.ts
news:any
constructor(private ns:NewsserviceService,private cd:ChangeDetectorRef) { }
ngOnInit() {
this.news= this.ns.getNewsList();
console.log("news is" +this.news)
}
}
当我点击任何类别时,我会第一次在控制台中从 Newslist 组件中获取数据,但之后我没有从 newsList 组件中获取任何数据,但我在控制台中从 Newservice 获取数据
【问题讨论】:
-
由于 CORS 问题,您的 stackblitz 无法正常工作。你能用一个简单的例子重现你的问题,而不是把你的整个项目复制到一个堆栈闪电战中吗?
-
我已经更新了。你能检查一下吗!!!
-
也许不是将数据保存到服务上的变量中,而是尝试使用 observables:angular.io/guide/…
-
我不明白你的问题。你能清楚地说明重现问题的步骤吗
-
您的子组件不监听父组件的 onClick 事件,因此他们无法更新 html 上的数据!您可以为此使用 eventEmiter
标签: angular angular6 angular7 angular8 angular-services