无法使用服务

时间:2016-10-12 13:02:08

标签: javascript angular angular2-services

我创建了通过社交网络登录的服务, 我的问题是我在尝试使用它时遇到错误。 我的主要成分是:

import {Component, ViewEncapsulation} from '@angular/core';
import {UserData} from '../../theme/services/userData';
@Component({
  selector: 'login',
  encapsulation: ViewEncapsulation.None,
  styles: [require('./login.scss')],
  template: require('./login.html'),
})
export class Login {
  constructor(public _userData: UserData) {

  }

  login(form: string) {
    this._userData.login(form);

  }

服务:

import {Injectable} from '@angular/core';
import {AngularFire, AuthProviders} from 'angularfire2';
@Injectable()
export class UserData {
  user = {};
  isAuth = false;

  constructor(public af: AngularFire) {
    debugger;
    this.af.auth.subscribe(user => this._changeState(user));
  }

错误是:

  

error_handler.js:46 EXCEPTION:未捕获(在承诺中):错误:./Login类中的错误Login_Host - 内联模板:0:0由以下原因引起:UserData没有提供者!ErrorHandler.handleError @ error_handler.js:46next @ application_ref.js:291schedulerFn @async.js:89SafeSubscriber .__ tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js: 55EventEmitter.emit @ async.js:81onError @ ng_zone.js:123onHandleError @ ng_zone_impl.js:65ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386   error_handler.js:51 ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:51next @ application_ref.js:291schedulerFn @async.js:89SafeSubscriber .__ tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber。 js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:81onError @ ng_zone.js:123onHandleError @ ng_zone_impl.js:65ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386   error_handler.js:52错误:未捕获(在承诺中):错误:./Login类中的错误Login_Host - 内联模板:0:0引起:UserData没有提供者!

2 个答案:

答案 0 :(得分:1)

错误消息说明了所有内容:No provider for UserData!

您需要使用provide数组UserData app.module.ts providers @NgModule({ imports: [ BrowserModule, ], declarations: [ AppComponent ], providers: [ UserData ], bootstrap: [AppComponent] }) export class AppModule { } 服务,如下所示:

{{1}}

答案 1 :(得分:0)

您是否已将NgModule内的UserData注册到providers数组?