angular-cn/public/docs/_examples/pipes/ts/app/fetch-json.pipe.ts

29 lines
643 B
TypeScript
Raw Normal View History

// #docregion
2016-04-27 14:28:22 -04:00
import {Pipe, PipeTransform} from '@angular/core';
import {Http} from '@angular/http';
// #docregion pipe-metadata
@Pipe({
name: 'fetch',
pure: false
})
// #enddocregion pipe-metadata
export class FetchJsonPipe implements PipeTransform{
private fetched:any = null;
private prevUrl = '';
constructor(private _http: Http) { }
2016-04-20 20:12:21 -04:00
transform(url: string): any {
if (url !== this.prevUrl) {
this.prevUrl = url;
this.fetched = null;
this._http.get(url)
.map( result => result.json() )
2016-04-20 20:12:21 -04:00
.subscribe( result => this.fetched = result );
}
return this.fetched;
}
}