【发布时间】:2018-09-29 23:11:22
【问题描述】:
我正在尝试从角度服务订阅变量的更改,而不是在组件中订阅它。这是我测试的代码:
服务:
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 将使用输入进行更改
【问题讨论】:
-
您正在寻找
BehaviorSubject(接收推送更新),而不是计划Subject -
@Z.Bagley 我试过了,但它只在第一次加载页面时有效。
标签: angular