观看角度变化

时间:2018-09-29 23:11:23

标签: angular

我正在尝试从角度服务中订阅变量的更改,而不在组件中订阅它。这是我测试过的代码:

服务:

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

@Injectable()

export class testService {
  detectChanges = new Subject();
  myObject : any = {
    test:"Test"
  };
  constructor() {
    this.detectChanges.subscribe((data) => {
      console.log("changed");
    });
  }
}

组件:

import { Component } from '@angular/core';
import { testService } from './test-service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  $s;
  constructor(private test: testService) {
    this.$s = this.test.myObject;
  }
}

html:

<input [(ngModel)]="$s.test">
<h1>{{$s.test}}</h1>

有没有办法做到这一点?就像在angularjs $watch中一样 这是一个示例https://stackblitz.com/edit/angular-cmyy66?file=src%2Fapp%2Fapp.component.html 在示例中,myObject将使用输入进行更改

3 个答案:

答案 0 :(得分:0)

您可以为此使用设置器:

服务:

 private _myObject;
 public get myObject() { return this._myObject; };
 public set myObject(val) { 
     console.log("The value is changing");
     this._myObject = val
 };

在组件中:

 constructor(public test: testService) {
    this.test.myObject="New test"; // This would cause "The value is changing" to be logged
 }

如果愿意,您可以在set函数中也通知主题

Here is a StackBlitz demo

答案 1 :(得分:0)

我已经在stackblitz

上创建了一个示例

基本上,您的服务如下所示:

@Injectable()
export class TestService{
  private detectChanges: Subject<any> = new Subject<any>();
  myobject$ = this.detectChanges.asObservable();

 constructor() {
   this.detectChanges.subscribe((data) => {
     console.log("changed", data);
   });
 }

 changeObject(myobject: any) {
   this.detectChanges.next(myobject);
 } 
}

订阅并更改您的主题

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  constructor(private testService: TestService) {
    this.testService.myobject$.subscribe((data) => {
      this.name = data;
    });
  }

  change(input) {
    this.testService.changeObject(input);
  }
}

希望有帮助。

答案 2 :(得分:0)

使用BehaviorSubject和getter / setter的最简单解决方案;

@Injectable()
export class testService {
  myObject: any = {
    _test$: new BehaviorSubject("Test"),
    set test(val) {
      this._test$.next(val);
    },
    get test() {
      return this._test$.getValue();
    }
  };
  constructor() {
    this.myObject._test$.subscribe((data) => {
      console.log("changed", data);
    });
  }
}

还可以看看OnChanges