观察angular2,typescript中的服务更改和更新组件

时间:2016-08-22 07:42:01

标签: angular typescript rxjs observable

我有一个组件和服务。我想在服务中的布尔属性发生变化时通知我的组件。我想我应该使用rxjs的Observable和Observer。

我使服务和组件无法正常工作。

AppComponent.ts

interface ColumnHeader {
    header: string;
    text: string;
    headerImage: string;
    buttonText: string;
}

interface MyData {
    carousel: any[];
    "column-headers": ColumnHeader[];
}

let o = {
    "carousel": [],
    "column-headers": [{
        "header": "Heading",
        "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.",
        "headerImage": "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        "buttonText": "View details"
    }, {
        "header": "Heading",
        "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.",
        "headerImage": "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        "buttonText": "View details"
    }, {
        "header": "Heading",
        "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.",
        "headerImage": "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        "buttonText": "View details"
    }]
} as MyData;

let header = o["column-headers"][0]; // typeof header is ColumnHeader
let image = header.headerImage; // typeof image is string

UserDataService.ts

import {  Component } from '@angular/core';
import { UserData } from 'user-data.service';
@Component({
    selector: 'app',
    templateUrl: '<div></div>'
})
export class AppComponent {
    isLoggedIn: boolean;
    constructor(public userData: UserData) {
       userData.isLoggedIn.subscribe(isLoggedIn => {
           this.isLoggedIn = isLoggedIn;
       });//???
    }
    ???
}

}

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用带有初始值的BehaviorSubject

export class UserData {
  isLoggedIn: Subject<bool> = new BehaviorSubject(false);
  changeLoginStatus (isLoggedIn: boolean) { 
    this.isLoggedIn.next(isLoggedIn); // ??? not sure
  } 
}

另见https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

正如@KonradGarus建议的那样,Subject应该保密。

export class UserData {
  private isLoggedIn: Subject<bool> = new BehaviorSubject(false);
  isLoggedIn$ = this.isLoggedIn.asObservable();
  changeLoginStatus (isLoggedIn: boolean) { 
    this.isLoggedIn.next(isLoggedIn); 
  } 
}

上面链接的食谱还包含Subject保密的完整示例。