@Output from service

I am using Angular CLI. Actually, I have a service. This service return variable answer . I would like to use the variable in app-component(or dublicate of the variable). So when answer change, It must be seen in the app-component. Now I can see onle initiial value of the variable and don't see changed answer.

service:

import { Injectable } from '@angular/core';
import { CanActivate }    from '@angular/router';

@Injectable()
export class LogInGuardService implements CanActivate {


public answer: boolean;
public i: number = 0;


    canActivate() {
        let entered = JSON.parse(localStorage.getItem('enteredValue'));

        let enteredEmail = entered.email_field;
        let enteredPw = entered.password_field;
        let guardChange = false;
        for (var i = 1; i < localStorage.length; i++) {

            let stored = JSON.parse(localStorage.getItem(localStorage.key(i)));
            let storedEmail = stored.email_field;
            let storedPw = stored.password_field;


            if ( enteredEmail == storedEmail )  {

                if ( enteredPw == storedPw ) {
                    this.answer = true;


                } else {
                    alert('Неверный пароль');
                    this.answer = false;
                }

            } else {
                this.i++;
            }
        }

        if (this.i == localStorage.length-1) {
            alert('Пользователя с таким e-mail не существует');
        }
    return this.answer;
  }

  constructor() { }

}

app-component:

import { Component } from '@angular/core';
import { LogInGuardService } from './log-in-guard.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

    public guardInMain: boolean;

    constructor(private loginService: LogInGuardService) {

        this.guardInMain = true;

        this.guardInMain = !this.loginService.answer;

    }
    }

1 answer

  • answered 2017-11-12 23:59 Martin Nuc

    If you want to store some variable in your service you can use Observables for that.

    Use BehaviorSubject for that. Subject is both observable and observer. So you can tell it there is a new answer and it will notify all subscribers.

    In your service:

    answer$ = new BehaviorSubject<string>('');
    getAnswer(): Observable<string> {
        return this.answer$.asObservable();
    }
    
    giveAnswer(answer: string) {
        this.answer$.next(answer);
    }
    

    Notice that constructor accepts the initial value.

    You can set new answer:

    AnswerService.giveAnswer('this is my answer');
    

    And you can subscribe anywhere for value changes:

    AnswerService.getAnswer().subscribe(answer => console.log(answer));