0

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?

1 Answer 1

1

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;
        });
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I must be missing something. For whatever reason your code does not do anything.
Nvm. Got it. I moved setWorking to the bottom.
can you make MainService line var text$ = function(){ return this.textSource;} and try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.