【问题标题】:Angular 2 http change value in response not affect the pageAngular 2 http响应更改值不影响页面
【发布时间】:2016-09-22 09:38:55
【问题描述】:

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

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

}

【问题讨论】:

    标签: javascript angularjs http angular angular2-http


    【解决方案1】:

    当您使用function 时,您将丢失当前thisclass。您应该在 observable 的 successerror 函数中使用箭头函数。 function () {} 应该是 () =&gt; {}

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

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多