问题
ive been trying to make Angular update the service variable "open_popup" for days with no luck.
TLDR; What I'm trying to do, is whenever the variable "open_popup" changes, make it change on the component too also be able to change the service variable from a component function.
This is what I've tried so far.
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.
doesn't work
{{ this.popup_is_open }}
PS: just tried to hack the function directly into the template and it works so there must be something wrong with the way im binding the component variable??
{{ audience_creator_service.popupIsOpen().value }}
回答1:
@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();
}
}
来源:https://stackoverflow.com/questions/51545856/how-to-watch-service-variable-in-angular-6