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

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

问题描述

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

代码如下:

app.component.html

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"><ul class="nav navbar-nav navbar-right"><ol class="面包屑"><li *ngFor="let lang of langs"><a (click)="changeLanguage(lang)">{{ 朗}}</a></ol>

</nav><路由器插座></路由器插座>

app.component.ts

import { Component } from '@angular/core';导入'./rxjs-operators';从'@angular/router' 导入 { ROUTER_DIRECIVES };从'./lang.service'导入{LangService};从 './notes/notes.component' 导入 { NotesComponent };@成分({模块 ID:module.id,选择器:'app-root',templateUrl: 'app.component.html',styleUrls: ['app.component.css'],指令:[NotesComponent, ROUTER_DIRECIVES],提供者:[LangService]})导出类 AppComponent {title = "BSC-Ideas 的笔记应用程序";langs :Array= ['EN', 'CZ'];构造函数(私人 _langService :LangService){this._langService.activeLang$.subscribe(成功 =>console.log('done')//这里有效);}更改语言(语言:字符串):无效{this._langService.changeLanguage(lang);}}

一些 other.component.ts

import { Component, OnInit } from '@angular/core';从'../lang.service'导入{LangService};@成分({模块 ID:module.id,选择器:'所有笔记',templateUrl: 'notes.component.html',提供者:[NoteService, LangService]})导出类 NotesComponent 实现 OnInit {模式 = '可观察';构造函数(私有 _langService :LangService){}ngOnInit() {this.updatePhrases(this.postPhrases);this._langService.getUpdates().subscribe(成功 =>console.log('is working')//这里不起作用);}}

语言服务

import { Injectable } from '@angular/core';从 'rxjs/Observable' 导入 { Observable };从rxjs/主题"导入{主题};@Injectable()导出类 LangService {activeLang = 'EN';private activeLangSubject = new Subject();activeLang$ = this.activeLangSubject.asObservable();getUpdates() :Observable{返回 this.activeLang$.map(响应=>回复 ||{});}更改语言(语言:字符串){if(lang == 'EN' || lang == 'CZ'){this.activeLang = lang;this.activeLangSubject.next(lang);}}}

感谢您的帮助.

解决方案

如果你在每个组件上提供LangService,每个组件都会有自己的实例.

改为只在根组件或 bootstrap(AppComponent, [LangService])

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

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.

Here is the code:

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

}

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

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

}

Thank you for your help.

解决方案

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

Instead provide it only once at the root component or bootstrap(AppComponent, [LangService])

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天全站免登陆