Angular 2没有更新HTTP获取呼叫返回的视图



当AJAX调用返回时,我正在更改应用程序组件中的列表属性,但我的视图没有相应地更新。

这是组件:

import {Component} from '@angular/core';
import {ValuesService} from "./services/ValuesService";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ValuesService]
})
export class AppComponent {
  values: string[];
  constructor(private valuesService: ValuesService) {
    this.values = ['1', '2'];
  }
  onClick() {
    this.valuesService.getValues().subscribe(this.onValues)
  }
  onValues(values: string[]) {
    for (let value of values) {
      console.log(value);
    }
    this.values = values // this should change the view
  }
}

查看:

<button (click)="onClick()">Hit Me</button>
<div *ngFor="let value of values">
  <h3>{{value}}</h3>
</div>

单击按钮时,我确实在控制台中看到:

received value1,value2,value3
app.component.ts:27 value1
app.component.ts:27 value2
app.component.ts:27 value3

但是,视图不会改变。

什么可能导致这个问题?这是我在package.json中的依赖项:

  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },

编辑:

修复是更改:

this.valuesService.getValues().subscribe(this.onValues)

to

this.valuesService.getValues().subscribe(values => this.onValues(values))

看起来像this.values = dureation this.onvalues并未将"此"评估给应用程序,而是对函数本身进行评估。这与范围有关。

猜想...这可能是 this 的正常范围此在功能级别。因此,它可能不会引用类属性。我通常使用围绕此问题的箭头功能。这样的东西:

this.productService.getProducts()
        .subscribe(products => this.products = products,
                   error => this.errorMessage = <any>error);

由于它在箭头函数中,因此this在这里引用类属性。

查看此信息以获取更多信息:https://github.com/microsoft/typescript/wiki/'this'-in--typescript

最新更新