javascript - 响应中的 Angular 2 http 更改值不影响页面

标签 javascript angularjs http angular angular2-http

我对 Angular 2 很陌生。我试图在从将在页面中使用的参数的 http 请求获得响应后更改值。我不明白为什么即使控制台日志中的值已更改,它也不会影响页面。

页面.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>

页面.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';
        }
    );

}

最佳答案

当您使用function 时,您将丢失class 的当前this。您应该在 Observable 的 successerror 函数中使用 Arrow 函数。 function () {} 应该是 () => {}

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';
        }
    );
}

关于javascript - 响应中的 Angular 2 http 更改值不影响页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39635486/

相关文章:

javascript - 数据上没有显示任何内容

javascript - 如何用ngdocs描述一个提供函数集合的返回对象?

javascript - AngularJS 通过 $compile 获取动态内容的范围未附加到 Controller 范围

javascript - 自动http过期

javascript - wcf 服务无法从 ie 中运行的 javascript 解析日期时间

javascript - 无法禁用动态 div 中的元素

javascript - Angular 访问 Controller 内的 cookie

java - 如何保留或 hibernate http 请求,直到服务器端完成某些处理?

java - 如何知道 HTTP 服务器何时完成发送数据

javascript - 实时协作编辑器 API