Listen to changes on mock-service in Angular 2

Dawid Zbiński

I'm building an app where you can change between two languages any time you want. I've got a mock-service that provides me the phrases I use. When the user clicks on language link, the language in mock-service is changed, but I need to somehow listen to the changes when I'm getting the phrases, so service is returning me the updated phrase in Language I want.

LangService.ts:

activeLang :string = 'EN';
getPhrase(phrase :string) :string{
    if(this.activeLang == 'EN'){
      return this.EN[phrase]; 
    } else {
      return this.CZ[phrase];
    }
  }

  changeLanguage(lang :string) :void{
    if(lang == 'EN' || lang == 'CZ'){
      this.activeLang = lang;
    }
  }

Then some OtherComponent.ts:

setPhrase(phrase :string){
    this._langService.getPhrase(phrase);
    // Here I need to subscribe to getPhrase to get the latest updates
    // If I'm right and if it's possible
  }

UPDATE

I made some corrections. LangService now has the Observable that we can listen to, but listener only works for component that triggers the method changeLanguage(). I want to be able to change the language from my NavigationComponent and catch the change in some OtherComponent.

LangService.ts:

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

@Injectable()
export class LangService {
private activeLang = 'EN';
private activeLangSubject = new Subject<string>();
activeLang$ = this.activeLangSubject.asObservable();

// Objects EN and CZ with properties, etc.

getPhrases(phrases :Array<string>){
  if(this.activeLang == 'EN'){
    let response = <any>{};
    for(let i = 0; i < phrases.length; i++){
      response[phrases[i]] = this.EN[phrases[i]];
    }
    console.log('refresh');
    return JSON.stringify(response);
  } else {
    let response = <any>{};
    for(let i = 0; i < phrases.length; i++){
      response[phrases[i]] = this.CZ[phrases[i]];
    }
    return JSON.stringify(response);
  }
}

changeLanguage(lang :string){
  if(lang == 'EN' || lang == 'CZ'){
    this.activeLang = lang;
    this.activeLangSubject.next(lang);
  }
}

NavComponent.ts:

import { Component, OnInit } from '@angular/core';
import { LangService } from '../lang.service';

@Component({
  moduleId: module.id,
  selector: 'app-nav',
  templateUrl: 'nav.component.html',
  styleUrls: ['nav.component.css'],
  providers: [LangService]
})
export class NavComponent implements OnInit {
  langs :Array<string> = ['EN', 'CZ'];

  constructor(
    private _langService :LangService) {
  }

  changeLanguage(lang :string) :void{
    this._langService.changeLanguage(lang);
  }
}

with NavComponent.html:

<li *ngFor="let lang of langs">
  <a (click)="changeLanguage(lang)">{{ lang }}</a>
</li>

OtherComponent.ts:

import { Component, OnInit } from '@angular/core';
import { LangService } from '../lang.service';
import { NavComponent } from '../nav/nav.component';

@Component({
  moduleId: module.id,
  selector: 'all-notes',
  templateUrl: 'notes.component.html',
  providers: [NoteService, LangService],
  directives: [NavComponent]
})
export class NotesComponent implements OnInit {

  mode = 'Observable';

  postPhrases :Array<string> = [
    "alertTitle", "alertText", "options", "detailsBtn","editBtn","deleteBtn", 
    "addBtn", "serverResp", "actionMessage", "responseMessage", "note"
  ];

  getPhrases :Object;

  constructor(
    private _langService :LangService) {
  }

  ngOnInit() {
    this.updatePhrases(this.postPhrases);

    // This one doesn't work 
    this._langService.activeLang$.subscribe(
      success => this.updatePhrases(this.postPhrases),
      error => console.log(error),
      () => console.log('complete')
    );
  }

  updatePhrases(phrases :Array<string>) :void {
    this.getPhrases = JSON.parse(this._langService.getPhrases(phrases));
  }

}

My question now is how can I listen for the changes on OtherComponent, so I can use method updatePhrases() to update phrases.

Dawid Zbiński

So basically the whole thing I needed was to create a service LangService with 3 variables.

activeLang: string 'EN';
activeLangSubject: Subject<string> = new Subject<string>();
activeLangObservable: Observable<string> = this.activeLangSubject.asObservable();
  1. activeLang - variable for comparing the languages,
  2. activeLangSubject - variable for creating an Observable,
  3. activeLangSubject - variable that we can subscribe to

After that, I needed to add the LangService to the right scope. I wanted that to be global, so I put it as a provider to bootstrap method in main.ts file.

bootstrap(AppComponent, [LangService]);

Of course I needed to import it before providing it to bootstrap.

After providing it in bootstrap all I needed to do was:

  • Import it to every component that needed to listen to the changes,
  • NOT to provide it there as we have global instace of it and we don't want to create other,
  • Inject it in constructor constructor(private _langService: LangService) {},
  • Subscribe to it

    ngOnInit() { this._langService.langServiceObservable.subscribe( response => console.log('Changed! Active Language: ' + response), error => console.log('Error! Description: ' + error) ); }

In case you don't use ngOnInit() you can also subscribe to changes inside constructor()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Angular 2 Component listen to change in service

From Dev

Test Angular2 service with mock backend

From Dev

Implement HTTP service mock for Angular 2?

From Dev

Is there any way to listen to changes on an input range in Angular 2?

From Dev

how can I listen to changes in code in angular 2?

From Dev

Listen to Changes on an Object's field in Angular2/Typescript

From Dev

how can I listen to changes in code in angular 2?

From Dev

Angular2 directive listen to parent component callbacks or changes

From Dev

Angular2 - subscribe to Service variable changes

From Dev

Angular2 - subscribe to changes in service data

From Dev

How to listen changes in routing Angular?

From Dev

Angular2/testing: how to run test with mock service provider?

From Dev

Angular 2 - how do I mock a service being called in a component?

From Dev

Angular 2 Two-way Binding updates mock service constant

From Dev

Injecting mock angular service dependencies

From Dev

Watch for changes in service and update component in angular2, typescript

From Dev

Angular 2 not detecting changes in service variable from component

From Dev

Angular. Watching a service for changes?

From Dev

How to read data and listen to changes from Room database in a Service?

From Dev

Angular 2 listen on model change

From Dev

How to mock Angular $q service in Jasmine test?

From Dev

mock angular service/promise in a karma/jasmine test

From Dev

Angular and Jasmine: how to mock a service that returns a promise

From Dev

Mock service injected into Angular module run block

From Dev

Mock angular service not being detected in jasmine?

From Dev

jasmine testing a mock service in an angular 1.5 controller

From Dev

Angular 2 mock response not working

From Dev

Angular 2 How do I call a service method when an observable changes/when a services returns new results?

From Dev

How to mock Symfony 2 service in a functional test?

Related Related

  1. 1

    Angular 2 Component listen to change in service

  2. 2

    Test Angular2 service with mock backend

  3. 3

    Implement HTTP service mock for Angular 2?

  4. 4

    Is there any way to listen to changes on an input range in Angular 2?

  5. 5

    how can I listen to changes in code in angular 2?

  6. 6

    Listen to Changes on an Object's field in Angular2/Typescript

  7. 7

    how can I listen to changes in code in angular 2?

  8. 8

    Angular2 directive listen to parent component callbacks or changes

  9. 9

    Angular2 - subscribe to Service variable changes

  10. 10

    Angular2 - subscribe to changes in service data

  11. 11

    How to listen changes in routing Angular?

  12. 12

    Angular2/testing: how to run test with mock service provider?

  13. 13

    Angular 2 - how do I mock a service being called in a component?

  14. 14

    Angular 2 Two-way Binding updates mock service constant

  15. 15

    Injecting mock angular service dependencies

  16. 16

    Watch for changes in service and update component in angular2, typescript

  17. 17

    Angular 2 not detecting changes in service variable from component

  18. 18

    Angular. Watching a service for changes?

  19. 19

    How to read data and listen to changes from Room database in a Service?

  20. 20

    Angular 2 listen on model change

  21. 21

    How to mock Angular $q service in Jasmine test?

  22. 22

    mock angular service/promise in a karma/jasmine test

  23. 23

    Angular and Jasmine: how to mock a service that returns a promise

  24. 24

    Mock service injected into Angular module run block

  25. 25

    Mock angular service not being detected in jasmine?

  26. 26

    jasmine testing a mock service in an angular 1.5 controller

  27. 27

    Angular 2 mock response not working

  28. 28

    Angular 2 How do I call a service method when an observable changes/when a services returns new results?

  29. 29

    How to mock Symfony 2 service in a functional test?

HotTag

Archive