代码之家  ›  专栏  ›  技术社区  ›  Prateek Ratnaker

更新服务中声明的变量时更新组件变量

  •  0
  • Prateek Ratnaker  · 技术社区  · 6 年前

    当服务中声明的变量更改时,我正在尝试更新组件中声明的变量。我正在使用主题。然而,什么都没有发生。

    应用程序。单元ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    
    import { AppComponent } from './app.component';
    import { ShareDataService } from './share-data.service';
    
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule
      ],
      providers: [ShareDataService],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    应用程序。组成部分ts

    import { Component } from '@angular/core';
    import { ShareDataService } from './share-data.service';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'app';
      _subscription;
      constructor(private shareDataService:ShareDataService)
      {
        //this.title=this.shareDataService.title;
        this._subscription = shareDataService.titleChange.subscribe((value) => { 
          this.title = value; 
          //alert(this.title);
          console.log("COmponent::::::::::::::"+this.title);
        });
      }
    }
    

    shareDataService。ts

    import { Injectable } from '@angular/core';
    import { Subject } from 'rxjs/Subject';
    @Injectable()
    export class ShareDataService {
      title:string="TITLE";
      titleChange: Subject<string> = new Subject<string>();
      constructor() {
        setTimeout(
          function()
          {
    
          this.title="BACDEF";
    
          //console.log(this.title);
          this.titleChange.next(this.title);
        }
        ,1000);
       }
    }
    

    对于服务中定义的主题,它会给出一个错误消息“无法读取未定义的属性‘next’”。实现这一点最合适的方式是什么?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Julius Dzidzevičius    6 年前

    使用箭头功能:

    setTimeout(() => {
      this.title="BACDEF";
      this.titleChange.next(title);
    }, 1000)
    

    或绑定:

    setTimeout(function() {
      this.title="BACDEF";
      this.titleChange.next(title);
    }.bind(this), 1000)
    

    以消除该错误。否则 this 在setTimeout的回调中是一个窗口对象

        2
  •  1
  •   cyberpirate92    6 年前

    实现这一点最合适的方式是什么?

    您可以使用 BehaviorSubject 而不是 Subject 因为

    • 订阅时,BehaviorSubject返回最后一个值,而 主题 直到 onnext ,因此使用 行为主体 无论何时订阅,您都不必担心组件拥有最新数据。

    • 如果要检索 行为主体 在不可观察的代码(无订阅)中,始终可以使用 getValue() 方法

    StackBlitz