2017-08-15 29 views
0

我想从一个JSON响应results场,但是我得到Property 'results' does not exist on type 'AppComponent住宅“结果”的类型不存在“AppComponent”

import { Component } from '@angular/core'; 

//in place where you wanted to use `HttpClient` 
import { HttpClient } from '@angular/common/http'; 



@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 

export class AppComponent { 
    title = 'app'; 

    // Inject HttpClient into your component or service. 
    constructor(private http: HttpClient) {} 
    ngOnInit(): void { 

    // Make the HTTP request: 
    this.http.get('assets/api/list.json').subscribe(data => { 

     // Read the result field from the JSON response. 
     this.results = data['results']; 

    }); 
    } 
} 

回答

1

这是因为打字稿编译器会检查results变量存在错误/在任何方法中使用它之前在类中初始化。

export class AppComponent { 
    title = 'app'; 
    results: any[]; //define it here 

    // Inject HttpClient into your component or service. 
    constructor(private http: HttpClient) {} 
    ngOnInit(): void { 

    // Make the HTTP request: 
    this.http.get('assets/api/list.json').subscribe(data => { 

     // Read the result field from the JSON response. 
     this.results = data['results']; 

    }); 
    } 
} 
相关问题