无法从Angular 2中的组件中的服务获取数据

时间:2016-05-03 19:24:32

标签: service angular promise components provider

我正在使用Angular 2.0.0-beta.15。我试图从组件中的服务获取数据。以下是组件中的一段代码。

import {Component} from 'angular2/core';
import {UserService} from '../services/user.service';
@Component({
  selector: 'parent',
  templateUrl: './views/parentUser.html',
  providers: [UserService]
})
export class ParentUserComponent {  
  constructor(private _userService:UserService) {
    this._userService.getCurrentUser().subscribe(data => console.log(data));
  }
}

现在我的UserService代码是

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

@Injectable()
export class UserService {
  private currentUser = {
        username: '',
        role: '',
        targetURL: ''
  };

  setCurrentUser(currentUser) {
    this.currentUser.username = currentUser.username;
    this.currentUser.role = currentUser.role;
    this.currentUser.targetURL = currentUser.targetURL;
    console.log('current User:' + JSON.stringify(this.currentUser));
  }

  getCurrentUser() {
    return Observable.of(this.currentUser);
  }
}

我的boots.ts如下:

///<reference path="../../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES, RouteConfig, Location,      LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {AppComponent} from './app.component';
import {HTTP_PROVIDERS} from 'angular2/http';
import {UserService} from './services/user.service';
import 'rxjs/Rx';

bootstrap(AppComponent, [ROUTER_PROVIDERS, HTTP_PROVIDERS,    provide(LocationStrategy, {useClass: HashLocationStrategy}), UserService]);

现在,当我尝试运行我的组件时。它会抛出错误 错误:未捕获(承诺):没有提供者! angular2-polyfills.js:528未处理承诺拒绝:没有提供者! NoProviderError {message:“没有提供者!,堆栈:”错误:DI异常↵在NoProviderError.BaseExc ... odules / angular2 / bundles / angular2.dev.js:11788:19)“,keys:Array [3],injectors :数组[3]}

有人可以指导我吗?

0 个答案:

没有答案