Observable在消息發佈者和觀察者Observer之間起到一個媒體中介的做用,Observer是真正須要接受信息的人。Observable的實例提供了一個訂閱函數,subscribe()。當Observable的實例接收到信息時,將Observer做爲參數傳遞給subscribe(),也就是經過subscribe()函數通知Observer,Observer接到通知後,使用next()方法再通知Observable()表示能夠傳數據了,而後Observer能夠一直接收到數據,直到發生error(),或是數據接收完成,complete();css
import {fromPromise} from 'rxjs'; const data = fromPromise(fetch('api/endpoint')); data.subscribe({ next(response){ console.log(response); }, error(err){ console.error('Error' + err); }, complete(){ console.log('Completed'); } });
import {interval} from 'rxjs'; //建立一個將要在計時器上發佈值的Observable const secondsCounter = interval(1000); //開始發佈值 secondsCounter.subscribe(n => console.log(`It is been ${n} seconds since subscribeing`));
import {fromEvent} from 'rxjs'; const el = document.getElementById('my-element'); const mouseMoves = fromEvent(el,'mousemove'); const subscription = mouseMoves.subscribe((evt:MouseEvent)=>{ console.log(`Cooeds:${evt.clientX} X ${evt.clientY} `); if(evt.clientX <40 && evt.clientY <40){ subscription.unsubscribe(); } });
4.經過ajax建立html
import {ajax} from 'rxjs/ajax'; const apiData = ajax('/api/data'); apiData.subscribe(res =>console.log(res.status,res.response));
//html文件 <zippy (open)="onOpen($event)" (close)="onClose($event)"></zipppy> //ts文件 @Component({ selector: 'zippy', template: ` <div class="zippy"> <div (click)="toggle()">Toggle</div> <div [hidden]="!visible"> <ng-content></ng-content> </div> </div>`}) export class ZippyComponent { visible = true; @Output() open = new EventEmitter<any>(); @Output() close = new EventEmitter<any>(); toggle() { this.visible = !this.visible; if (this.visible) { this.open.emit(null); } else { this.close.emit(null); } }
getHeroes(): Observable<Hero[]> { // this.messageService.add('HeroService:fetched heroes');//發送數據到緩存中 // return of(HEROES); // 這裏能夠改爲HttpClient.get<Hero[]>這裏也會返回一個Observable<Hero[]> // 採用RxJS中的of()方法模擬獲取數據 return this.http.get<Hero[]>(this.heroesUrl) .pipe( tap(heroes => this.log(`fetched heroes`)), catchError(this.handleError('getHeroes', [])) );
import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-routable', templateUrl: './routable.component.html', styleUrls: ['./routable.component.css'] }) export class Routable2Component implements OnInit { constructor(private activatedRoute: ActivatedRoute) {} ngOnInit() { this.activatedRoute.url .subscribe(url => console.log('The URL changed to: ' + url)); } }
import { FormGroup } from '@angular/forms'; @Component({ selector: 'my-component', template: 'MyComponent Template' }) export class MyComponent implements OnInit { nameChangeLog: string[] = []; heroForm: FormGroup; ngOnInit() { this.logNameChange(); } logNameChange() { const nameControl = this.heroForm.get('name'); nameControl.valueChanges.forEach( (value: string) => this.nameChangeLog.push(value) ); } }
參考:angular官方文檔react