0
votes

I have a very simple test component which looks like this:

@Component({
    selector: "test-component",
    template: "<div>Test</div>",
})
export class TestComponent implements OnInit {
    private test : number = 0;
    private service : ClientsService;

    constructor(s : ClientsService) {
        this.service = s;
    }

    public ngOnInit() {
        this.service.loadAllClients().subscribe(d => {
            this.test = 1;
        });
        let comp = this;
    }
}

The client service returns an Observable but my question is about the 'test' variable. After the component loads, the first and the first breakpoint is hit, the value of 'test' is 0 enter image description here However, when the breakpoint inside the 'subscribe()' is hit, the 'test' becomes undefined. Any assignments done inside the lambda do not take effect. enter image description here

What am I missing here to do proper assignment inside the 'subscribe()'?

1
I don't think you're missing anything. I think the actual JavaScript code obtained by transpiling the TypeScript uses another variable than this to refer to the component inside the callback. Print the value in the console, and see if it's printed properly. - JB Nizet

1 Answers

1
votes

One possibility (I'm not certain) is that this is scoping to the service, because you have an instance of it declared in your component. I haven't done that myself, so I'm not sure. You could try this to see if it works:

@Component({
    selector: "test-component",
    template: "<div>Test</div>",
})
export class TestComponent implements OnInit {
    private test : number = 0;

    constructor(private _service : ClientsService) {}

    public ngOnInit() {
        this._service.loadAllClients().subscribe(d => {
            this.test = 1;
        });
        let comp = this;
    }
}

Other than that, nothing looks wrong to me. I've used the above method many times, and that has preserved this for the component scope correctly.