我對angular2和rxjs相當陌生。我想創建一個angular2應用程序,會從jsonAPI一些數據,如何使用可觀察數據每5秒刷新一次數據
我想獲得的數據,每5秒, 我發現Observable.interval(5000)的解決方案,但我有一些錯誤,而編譯,
如何在ngOnInit()代碼中插入Observable.interval(500)代碼
請!
import { Component, OnInit } from '@angular/core';
import { IProduct } from './product';
import { ProductService } from './product.service';
@Component({
templateUrl: 'app/products/product-list.component.html',
styleUrls: ['app/products/product-list.component.css']
})
export class ProductListComponent implements OnInit {
pageTitle: string = 'Product List';
imageWidth: number = 50;
imageMargin: number = 2;
showImage: boolean = false;
listFilter: string;
errorMessage: string;
products: IProduct[];
constructor(private _productService: ProductService) {
}
toggleImage(): void {
this.showImage = !this.showImage;
}
ngOnInit(): void {
this._productService.getProducts()
.subscribe(products => this.products = products,
error => this.errorMessage = <any>error);
}
onRatingClicked(message: string): void {
this.pageTitle = 'Product List: ' + message;
}
}
productservice.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import { IProduct } from './product';
@Injectable()
export class ProductService {
private _productUrl = 'api/products/products.json';
constructor(private _http: Http) { }
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
getProduct(id: number): Observable<IProduct> {
return this.getProducts()
.map((products: IProduct[]) => products.find(p => p.productId === id));
}
private handleError(error: Response) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
爲什麼你刪除了答案? – Sajeetharan
我沒有刪除它! – user3264038
你標記了我的答案,然後將其刪除 – Sajeetharan