4

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 }}
2
  • Why don't you inject the service in the component constructor? Commented Jul 26, 2018 at 19:05
  • im passing the same service used in the app component as in <selector [audience_creator_service]="this.audience_creator_service"></selector> Commented Jul 26, 2018 at 19:07

1 Answer 1

5
@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();
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

"open_popup" property seems redundant. isOpen.value could be used instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.