angular--Observable總結

Observable的通俗理解


Observable在消息發佈者和觀察者Observer之間起到一個媒體中介的做用,Observer是真正須要接受信息的人。Observable的實例提供了一個訂閱函數,subscribe()。當Observable的實例接收到信息時,將Observer做爲參數傳遞給subscribe(),也就是經過subscribe()函數通知Observer,Observer接到通知後,使用next()方法再通知Observable()表示能夠傳數據了,而後Observer能夠一直接收到數據,直到發生error(),或是數據接收完成,complete();css

建立Observable對象的幾種情形


  1. 經過promise建立
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');
    	}
	});
  1. 經過counter建立
import {interval} from 'rxjs';
	//建立一個將要在計時器上發佈值的Observable
	const secondsCounter = interval(1000);
	//開始發佈值
	secondsCounter.subscribe(n =>
	console.log(`It is been ${n} seconds since subscribeing`));
  1. 經過事件建立
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));

angular中用到的Observable


  • EventEmitter:它是繼承於Observable的,可是又有了本身的emit(),用來將要發送的值傳遞給 observer.next();以下代碼:
//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);
   }
}
  • HttpClient:它從 HTTP 方法調用中返回了可觀察對象。例如,http.get(‘/api’) 就會返回可觀察對象
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', []))
      );
  • router:ActivatedRoute 是一個可注入的路由器服務,它使用Observable來獲取關於路由路徑和路由參數的信息;如:
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));
      }
    }
  • reactive forms:響應式表單,表單有些屬性用Observable來監聽表單控件的值;FormControl 的 valueChanges和 statusChanges 包含了會發出變動事件的Observable,如圖:
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

相關文章
相關標籤/搜索