2017-04-26 32 views
1

當我的應用程序組件中的列表屬性發生改變時,AJAX調用已經返回,但我的視圖沒有相應更新。Angular 2沒有更新HTTP上的視圖獲取調用返回

以下是部分:

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) 

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

看起來像this.values =值line.onValues中的內容不是評估應用程序的「this」,而是評估函數本身。這與範圍界定有關。

+0

你能變成一個plunker? – DeborahK

+0

@DeborahK嗯讓我看看我是否可以做到 –

回答

0

正如猜測......它可能是這個這個的正常範圍在功能級別。所以它可能不會引用類屬性。我通常使用一個箭頭函數來解決這個問題。事情是這樣的:

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

,因爲它是一個箭頭的功能,這裏的this被引用的類屬性。

檢查了這一點的詳細資料:https://github.com/Microsoft/TypeScript/wiki/「this'功能於打字稿

+0

確實,更改代碼爲「onClick(){ this.valuesService.getValues()。subscribe(values => this.values = values) }」的作品。謝謝你的幫助。現在,我如何避免使用lambda,而是調用onValues? –

+0

太棒了!真高興你做到了。 – DeborahK

+0

啊,知道了this.valuesService.getValues()。subscribe(values => this.onValues(values)) –