我一直试图让Angular在没有运气的情况下更新服务变量“ open_popup”。
TLDR; 我想做的是,每当变量“ open_popup”发生变化时,也使它在组件上也发生变化,还能够从组件函数中更改服务变量。
这是我到目前为止尝试过的。
app / src / app / audience-creator / shared / audience-creator.service.ts
import { Injectable } from "@angular/core";
import {Observable} from "rxjs/index";
import { of } from "rxjs/index";
@Injectable()
export class AudienceCreatorService {
constructor(private http: HttpClient) {}
public open_popup = false;
public toggleCreatorPopup() {
this.open_popup = !this.open_popup;
}
popupIsOpen(): Observable<any> {
return of(this.open_popup);
}
}
app / src / app / audience-creator / audience-creator.component.ts
import {Stuff} from "@angular/core";
@Component({
selector: 'audience-creator',
templateUrl: 'audience-creator.html'
})
export class AudienceCreatorComponent implements AfterViewInit, OnInit {
public popup_is_open = false;
@Input()
audience_creator_service;
ngOnInit() {
this.audience_creator_service.popupIsOpen().subscribe(
popup_is_open => this.popup_is_open = popup_is_open
);
}
}
app / src / app / audience-creator / audience-creator.html
--> {{ this.popup_is_open }} variable is always false.
不起作用
{{ this.popup_is_open }}
PS:只是试图直接将函数破解到模板中并且它起作用了,所以im绑定组件变量的方式一定有问题吗?
{{ audience_creator_service.popupIsOpen().value }}
答案 0 :(得分:4)
@Injectable()
export class AudienceCreatorService {
constructor(private http: HttpClient) {}
public open_popup = false
private isOpen: BehaviorSubject<boolean> = new BehaviorSubject(false);
public toggleCreatorPopup() {
this.open_popup = !this.open_popup;
this.isOpen.next(this.open_popup);
}
popupIsOpen(): Observable<any> {
return this.isOpen.asObservable();
}
}