订阅方法对更改无反应[Angular 2] [英] Subscribe method don't react to changes [Angular 2]

查看:76
本文介绍了订阅方法对更改无反应[Angular 2]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的app.component中有方法可以更改LangService中的语言.当发生更改时,由于我已预订所有组件中的更改,因此LangService应该使用Observable对象响应我的所有其他组件.不幸的是,这没有发生.它仅响应调用了用于更改语言的函数的app.component.我不确定我在哪里弄错了.也许当我刚接触Angular时,我只是误解了整个概念.

I've got the method in my app.component that changes languages in my LangService. When the change occurs the LangService should then response with Observable object to all my other components as I have subscribed to changes in all my components. Unfortunately, it's not happening. It only response to the app.component that called the function for changing the language. I'm not sure where I have made a mistake. Maybe I'm just misunderstanding the whole concept as I'm new to Angular.

这是代码:

app.component.html

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

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

some 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

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

}

谢谢您的帮助.

推荐答案

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

If you provide LangService on each component, each component will get its own instance.

相反,仅在根组件或bootstrap(AppComponent, [LangService])

如果使用RC.5将其添加到@NgModule()providers: [LangService]中,则它将成为全局服务autoall(除非它是延迟加载的模块,否则您需要使用forRoot())

If you use RC.5 add it to providers: [LangService] of the @NgModule() then it will become a global service automaticall (except when it's a lazy loaded module, then you need to use forRoot())

这篇关于订阅方法对更改无反应[Angular 2]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆