自动更新新JSON信息上的Angular页面

时间:2017-06-15 11:59:20

标签: angularjs json angular-cli

我有一个新闻应用,可以从服务中调用信息。我想这样做,当有新闻时,它会自动添加到页面中。

首先,我尝试在this.router.navigate(['/news'])方法中使用setInterval来实现此目的,但这会产生一个问题,即如果我更改页面(它是单页网站),则刷新重新连接到新闻页面。

因此,当我选择另一页时,我需要一些东西来刷新JSON信息,或者一种停止刷新的方法。

组件:

import { Component, OnInit } from '@angular/core';
import { NewsService } from '../services/news.service';
import { Router } from '@angular/router';

@Component({
    selector: 'app-news',
    templateUrl: './news.component.html',
    styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit
{
    //prop
    news: any;
    today =
    {
        releaseDate: Date()
    }


    //constructor
    constructor(private newsService: NewsService, public router: Router)
    {
        //getdata
        this.newsService.getNews().subscribe(response => this.news = response);
    }

    //methode
    Refresh()
    {
        //redirect
        setInterval(() =>
        {
            this.today.releaseDate = Date();
            //this.router.navigate(['/news']);
        }, 1000);
    }


    //lifeCycle
    ngOnInit()
    {
        this.Refresh()
    }
}

服务:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class NewsService
{

    //constructor
    constructor(private http: Http)
    {
    }

    //methode
    getNews()
    {
        return this.http.get('https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey={apikey}').map(response => response.json());
    }

和html:

<div>
    <h1 style="display:inline">Latest news</h1>
</div>
<h5 style="float:right">{{today.releaseDate|date:"HH:mm:ss"}}</h5>

<hr/>

<div *ngIf="news">
    <div class="newscontainer" *ngFor="let new of news.articles, let i =index">
        <div class="newsimage{{i%2}}">
            <img src="{{new.urlToImage}}">
        </div>
        <div class="newstitle">{{new.title}}</div>
        <hr />
        <div class="releasedate">Release date: {{new.publishedAt|date}} at {{new.publishedAt|date:"HH:mm"}}</div>
        <a href="{{new.url}}">Link to Article</a>
        <div class="synopsis">{{new.description}}</div>
    </div>
</div>

0 个答案:

没有答案