Achira Trakansutleart Achira Trakansutleart - 2 months ago 5
AngularJS Question

Angular 2 http change value in response not affect the page

I am quite new to angular 2. I am trying to change the value after getting response from http request of parameter that will be used in the page. I do not understand why it not affect at the page even though value have changed in the console log.

page.html



<ons-list>
<ons-list-header>Settings {{testMsg?testMsg:''}}</ons-list-header>
<ons-list-item>
<div class="center">
Enable VoLTE
</div>
<div class="right">
<ons-switch (change)="enabled()"></ons-switch>
</div>
</ons-list-item>
</ons-list>


page.ts



testMsg = 'before request';
enabled() {
let body = JSON.parse(this._settingService.load(this.pageName));
let url = this._settingService.loadUrl(this.pageName);
this._sesService.getCarsRestful().subscribe(
function (response) {
console.log("Success Response" + response);
this.test2 = response;
// this.showFrame = 'show';
// console.log(this.showFrame);
this.testMsg = 'after request';
console.log(this.testMsg);
},
function (error) { console.log("Error happened" + error) },
function () {
console.log("the subscription is completed");
// console.log(this.test2[0].name);
// this.showFrame = 'show';
}
);

}

Answer

When you use function you will lose the current this of class. You should use Arrow function in success and error function of observable. function () {} should be () => {}

testMsg = 'before request';
enabled() {
    let body = JSON.parse(this._settingService.load(this.pageName));
    let url = this._settingService.loadUrl(this.pageName);
    this._sesService.getCarsRestful().subscribe(
        //changed to arrow function
        (response) => {
            console.log("Success Response" + response);
            this.test2 = response;
            // this.showFrame = 'show';
            // console.log(this.showFrame);
            this.testMsg = 'after request';
            console.log(this.testMsg);
        },
        //changed to arrow function
        (error) => { console.log("Error happened" + error) },
        //changed to arrow function
        () => {
            console.log("the subscription is completed");
            // console.log(this.test2[0].name);
            // this.showFrame = 'show';
        }
    );
}
Comments