首页 文章

订阅方法不会对更改做出反应[Angular 2]

提问于
浏览
5

我的app.component中有方法可以更改LangService中的语言 . 当发生更改时,LangService应该使用Observable对象响应所有其他组件,因为我订阅了所有组件中的更改 . 不幸的是,它没有发生 . 它只响应调用该函数来改变语言的app.component . 我不确定我在哪里弄错了 . 也许我只是误解了整个概念,因为我是Angular的新手 .

这是代码:

app.component.html

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">                                           
        {{ title }}
      </a>
    </div>
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav navbar-right">
        <ol class="breadcrumb">
          <li *ngFor="let lang of langs">
            <a (click)="changeLanguage(lang)">
              {{ lang }}
            </a>  
          </li>
        </ol>
      </ul>
    </div>
  </div>
</nav>
<router-outlet></router-outlet>

app.component.ts

import { Component } from '@angular/core';
import './rxjs-operators';
import { ROUTER_DIRECTIVES } from '@angular/router'; 
import { LangService } from './lang.service';
import { NotesComponent } from './notes/notes.component';

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  directives: [NotesComponent, ROUTER_DIRECTIVES],
  providers: [LangService]
})
export class AppComponent {

  title = " Note App for BSC-Ideas";
  langs :Array<string> = ['EN', 'CZ'];

  constructor(
    private _langService :LangService
  ) {
    this._langService.activeLang$.subscribe(
      success => console.log('done') // It works here
    );
  } 

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

}

一些other.component.ts

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

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

  mode = 'Observable';

  constructor(private _langService :LangService) {}

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

    this._langService.getUpdates().subscribe(
      success => console.log('is working') //Doesn't work here
    );
  }

}

LangService

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

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

  getUpdates() :Observable<Object>{
    return this.activeLang$.map(
      response => response || {}
    );
  }

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

}

谢谢您的帮助 .

2 回答

  • 3

    如果在每个组件上提供 LangService ,则每个组件都将获得自己的实例 .

    而是只在根组件上提供一次或 bootstrap(AppComponent, [LangService])

    如果你使用 RC.5 将它添加到 @NgModule()providers: [LangService] 那么它将成为一个全局服务automaticall(除非它是一个延迟加载的模块,那么你需要使用 forRoot()

  • 1

    我想你需要在所有组件中共享 LangService 的实例 . 为此,仅在顶级组件中提供 LangService . 在你的情况下可能是app.component.ts

    您可以通过this文章详细了解依赖注入和提供程序 .

相关问题