2016-01-18 34 views
3

調用Ajax調用我有這個組件:爲什麼我無法從Angular2

import {Component} from 'angular2/core'; 
import {UserServices} from '../services/UserServices'; 

@Component({ 
    selector: 'users', 
    template: '<h1>HOLA</h1>' 
}) 

export class UsersComponent { 
    users: Object; 

    constructor(userServices: UserServices) { 
     userServices.getUsersList(); 
    } 
} 

,並在UserServices我有這樣的代碼:

import {Http} from 'angular2/http' 

export class UserServices { 
    users: Array<any>; 
    http: any; 

    constructor(http: Http) { 
     this.http = http; 
    } 

    getUsersList() { 
     this.http.get('./users.json').map((res: Response) => res.json()).subscribe(res => console.log(res)); 
    } 

} 

我要調用一個Ajax調用的users定製標籤。 但我發現了這個錯誤:

Cannot resolve all parameters for UserServices(?). Make sure they all have valid type or annotations.

當我刪除HTTP參數,進口和調用,它沒有任何錯誤,所以我想這個問題是存在的,但我不能找出問題

回答

6

您錯過了DI中相關部分的幾個部分。

使用provide@inject或使用@Injectable修飾符有多種注入方法。在這裏,你,例如,與@Injectable

import {Injectable} from 'angular2/core'; 
import {Http, Response} from 'angular2/http'; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 

// You do not need to do this, but creating an interface for more strong typing. You could as well create a User class here and use that as view model. 
interface IUser{ 
    name:string; 
} 

@Injectable() 
class UserServices { 
    users: Array<IUser>; 

    constructor(private http:Http) {} 

    getUsersList():Observable<Array<IUser>> { 
     return this.http.get('./users.json') 
      .map((res: Response) => res.json()); 
    } 

} 

export {IUser, UserServices}; 

進樣UserServicesHTTP_PROVIDERS在根裝飾你的服務,一般來說,你注入你的應用程序根級別需要爲單跨您的應用程序的服務。如果沒有,您可以在UserComponent修飾符的providers數組中單獨注入服務。

bootstrap(UsersComponent, [HTTP_PROVIDERS, UserServices]) 

或組件的裝飾中:

@Component({ 
    selector: 'users', 
    template: `<h1>Users</h1> 
    <div *ngFor="#user of users"> 
    {{user.name}} 
    </div> 

    `, 
    providers:[UserServices] 
}) 

消費這在組件和訂閱返回的觀測。

export class UsersComponent { 
    users: Array<IUser>; 

    constructor(userServices: UserServices) { 
     userServices.getUsersList().subscribe(users => this.users = users); 
    } 
} 

您還可以使用async pipe(這個應用程序取決於使用情況)並設置this.users值作爲可觀察到的,而不是明確訂閱他們。

<div *ngFor="#user of users | async"> 
    {{user.name}} 
</div> 

this.users = userServices.getUsersList(); 

注:在這個例子中,我只是進口map operator以獲取地圖,通過HTTP(import rxjs/add/operator/map)返回的觀察到的一個部分,因爲這不是映射在全局級別的系統Js config paths屬性中。

這是一個工作plunker Demo

+0

完美!非常感謝! – Pablo

+0

@Pablo歡迎您。 :) – PSL

+0

@PSL我有一個問題不涉及這個問題,如果你不介意。 「你多次使用'''''''我的意思是你爲什麼使用'Array '而不是'IUser []'?它是如何調用的,以及我可以在哪裏瞭解更多信息? – Eggy

1

服務需要一個Injectable()註釋

import {Injectable} from 'angular2/core'; 

@Injectable() 
export class UsersComponent { 

爲DI能夠注入Http或其他依賴於它的構造。

+1

你錯過了'@':P –

+0

是的。這聽起來很奇怪,但是在添加這些行後,我得到'SyntaxError:expected expression,got'<'o.O – Pablo

+0

我沒有解決方案。似乎沒有關係。 –

相關問題