angular - 订阅方法不对更改使用react[Angular 2]

标签 angular angular2-services angular2-observables

我的 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>

应用程序组件.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);
  }

}

一些其他的.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
    );
  }

}

语言服务

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

}

感谢您的帮助。

最佳答案

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

而是只在根组件或 bootstrap(AppComponent, [LangService])

提供一次

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

关于angular - 订阅方法不对更改使用react[Angular 2],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39166063/

相关文章:

angular - @ngx/store/update-reducers 意外地修改了我的应用程序的状态

angular - 错误 : No provider for ShopService! 在另一个服务中使用一个服务

angular - 在 Angular 2 中处理嵌套订阅的正确方法

javascript - 转换时间 hh :mm:ss into GMT time format in Angular 2

angular - 调用函数 SocialLoginModule,不支持函数调用。考虑用引用替换函数或 lambda

angular - 类型 'automaticDataCollectionEnabled' 中缺少属性 'FirebaseApp'

angular - 无法在 Angular2 中导入服务

javascript - Observable 成功后如何解析() Promise

node.js - ngFor 与 Observables?

javascript - 如何将 sqlite 扩展作为对象中的属性处理