Angular2在组件和服务之间传递变量

时间:2016-10-31 19:45:52

标签: angular

我正在尝试更好地理解Angular 2中组件和服务之间的传递值。

我的 main.service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MainService {
    private mainSource = new Subject<boolean>();
    main$ = this.mainSource.asObservable();

    private textSource = new Subject<string>();
    text$ = this.textSource.asObservable();

    setWorking(isWorking:boolean){
        this.mainSource.next(isWorking);
    }

    setTexting(isTexting:string){
        this.textSource.next(isTexting);
    }
}

我的 app.component

import { Component, OnInit } from '@angular/core';
import { MainService } from './main.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
    private subscription: Subscription;
    private textres: string;
    constructor(private mainService: MainService){}

    ngOnInit(){
        this.subscription = this.mainService.main$.subscribe(isWorking =>{
            if (isWorking){this.mainService.setTexting("Yeah");}
        });
        this.mainService.setWorking(true);
        this.textres = this.mainService.setTexting;
    }

}

我有一个mainSource,它是一个布尔值,并由我的组件订阅。这很好用。现在,我想通过textSource在我的组件和服务之间传递字符串值。

在初始化期间,我设置了setTexting('Yeah')的值,但我不知道如何在我的组件textres中调用它。

我如何获得this.mainService.setTexting的价值?

1 个答案:

答案 0 :(得分:1)

您访问setTexting值的代码将是

export class AppComponent implements OnInit {
    private subscription: Subscription;
    private textres: string;
    constructor(private mainService: MainService){}

    ngOnInit(){
        this.subscription = this.mainService.main$.subscribe(isWorking =>{
            if (isWorking){this.mainService.setTexting("Yeah");}
        });
        this.mainService.setWorking(true);

      // access to setTexting value 
      this.mainService.text$.subscribe(value =>{
            this.textres= value;
        });
    }
}