美文网首页
Angular 创建Observable 两种方式

Angular 创建Observable 两种方式

作者: 农夫_三拳 | 来源:发表于2019-06-13 18:37 被阅读0次

    1.Angular 2 RxJS Subject 应用

    message.service.ts

    import { Injectable } from '@angular/core';
    import {Observable} from 'rxjs/Observable';
    import { Subject } from 'rxjs/Subject';
    
    @Injectable()
    export class MessageService {
        private subject = new Subject<any>();
    
        sendMessage(message: string) {
            this.subject.next({ text: message });
        }
    
        clearMessage() {
            this.subject.next();
        }
    
        getMessage(): Observable<any> {
            return this.subject.asObservable();
        }
    }
    

    home.component.ts

    import { Component } from '@angular/core';
    import { MessageService } from '../_services/index';
    
    @Component({
        moduleId: module.id,
        templateUrl: 'home.component.html'
    })
    
    export class HomeComponent {
        constructor(private messageService: MessageService) {}
        
        sendMessage(): void { // 发送消息
            this.messageService.sendMessage('Message from Home Component to App Component!');
        }
    
        clearMessage(): void { // 清除消息
            this.messageService.clearMessage();
        }
    }
    

    app.component.ts

    import { Component, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs/Subscription';
    
    import { MessageService } from './_services/index';
    
    @Component({
        moduleId: module.id,
        selector: 'app',
        templateUrl: 'app.component.html'
    })
    
    export class AppComponent implements OnDestroy {
        message: any;
        subscription: Subscription;
    
        constructor(private messageService: MessageService) {
            this.subscription = this.messageService.getMessage()
                  .subscribe(message => { this.message = message; });
        }
    
        ngOnDestroy() {
            this.subscription.unsubscribe();
        }
    }
    
    1. 使用BehaviorSubject
    private testSubjcst = new BehaviorSubject<any>('');
    private testObservable = this.testSubjcst.asObservable();
    
    ngInit(){
      this.testSubjcst.next('1,2,2,3,4,5,5,6,47');
        this.testObservable.subscribe(next => {
          console.log(next);
        });
    }
    
    

    相关文章

      网友评论

          本文标题:Angular 创建Observable 两种方式

          本文链接:https://www.haomeiwen.com/subject/yllefctx.html