2016-01-18 82 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

我没有解决方案。似乎没有关系。 –

相关问题