角度2 rc - 无法读取属性'请求'未定义的

时间:2016-06-17 10:15:55

标签: angular request

这是我的代码,我无法弄清楚,也找不到解决问题的方法。如果答案存在于某处且无法找到,我很抱歉。

这是app.component.ts文件



import {Component} from '@angular/core';
import { HTTP_PROVIDERS} from '@angular/http';
import {SimpleHTTPComponent} from './simplehttp'


@Component({
  selector: 'my-app',
  providers: [HTTP_PROVIDERS],
  template: `
    <div>
      <simple-http></simple-http>
    </div>
  `,
  directives: [SimpleHTTPComponent]
})
export class AppComponent {
	
	data: Object;
	loading: boolean;
	constructor() {
  	}
}
&#13;
&#13;
&#13;

这是我的simplehttp.ts文件

&#13;
&#13;
import {Component} from '@angular/core';
import {Http, Response} from '@angular/http';
import { HTTP_PROVIDERS } from '@angular/http';
import {Inject} from '@angular/core'


@Component({
selector: 'simple-http',
template: `
	<h2>Basic Request</h2>
	<button type="button" (click)="makeRequest()">Make Request</button>
	<div *ngIf="loading">loading...</div>
	<pre>{{data | json}}</pre>`,
providers:[HTTP_PROVIDERS]
})
export class SimpleHTTPComponent {
	data: Object;
	loading: boolean;
	http: Http;
	constructor( @Inject(Http) private _http: Http){
		
	}
	makeRequest():void{
		this.loading = true;
		this.http.request('http://jsonplaceholder.typicode.com/posts/1')
		.subscribe((res: Response) => {
		this.data = res.json();
		this.loading = false;
		});
	}

}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

三个不需要多次提供HTTP_PROVIDERS

您的代码有错误。您注射_http但使用http

export class SimpleHTTPComponent {
    data: Object;
    loading: boolean;
    http: Http;

    // injects to local variable `_http`
    constructor( @Inject(Http) private _http: Http){}

    makeRequest():void{
        this.loading = true;
        // uses local variable `http` (without `_`)
        this.http.request('http://jsonplaceholder.typicode.com/posts/1')
        .subscribe((res: Response) => {
        this.data = res.json();
        this.loading = false;
        });
    }
}

应该是

export class SimpleHTTPComponent {
    data: Object;
    loading: boolean;

    constructor( @Inject(Http) private _http: Http){

    }
    makeRequest():void{
        this.loading = true;
        this._http.request('http://jsonplaceholder.typicode.com/posts/1')
        .subscribe((res: Response) => {
        this.data = res.json();
        this.loading = false;
        });
    }
}

如果构造函数参数具有访问修饰符privatepublic,那么这也会自动声明实例属性。