abrahamlinkedin abrahamlinkedin - 1 month ago 14
AngularJS Question

Angular2 passing variables between component and service

I am trying to better understand passing values between a component and a service in Angular 2.

My 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);
}
}


My 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;
}

}


I have a
mainSource
, which is a boolean, and is subscribed by my component. This works well. Now, I would like to pass string values in between my component and service through
textSource
.

During Init I have set the value of
setTexting('Yeah')
but I do not know how to call it in my component's
textres
.

How might I acquire the value of
this.mainService.setTexting
?

Answer

your code to access the value of setTexting would be

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;
        });
    }
}
Comments