简体   繁体   English

角度分量中的DI误差

[英]DI Error in Angular Component

I'm fairly new to Angular 2 and Typescript. 我是Angular 2和Typescript的新手。 I have a DI Error as below that I couldn't solve. 我有一个DI错误,我无法解决。 I was trying to understand how this DI works: 我试图了解这个DI是如何工作的:

I'm trying to build a simple signup component that uses a service for validation and REST API operations. 我正在尝试构建一个使用服务进行验证和REST API操作的简单注册组件。

Here is my component: 这是我的组件:

authentication.component.ts authentication.component.ts

import { Component, Injectable } from '@angular/core';
import { UserService } from './user.service';
import { User } from './user';


@Component({
    moduleId: module.id,
    selector: 'authentication',
    styles: ['input[type=email].ng-invalid {border: 1px solid #dd0000}'],
    template: `
    <h3>Sign Up</h3>
    <hr>

    <form (ngSubmit)="signup()" >
        <input type="email" name="email" required
        [(ngModel)]="user.email"/>
        <input type="password" name="password" required
        [(ngModel)]="user.password"/>
        <input type="submit" />
    </form>
    <span class.has-error>{{hasError}}</span>`
})
@Injectable()
export class AuthenticationComponent {

    public error: Error;
    public user: User;

    constructor(public userService: UserService) {}
    public signup(): void {
        this.userService.init(this.user);
        this.userService.signup().subscribe(
            s=>console.log(s),
            e=>console.log(e)
        )
    }

    get diagnostic () {
        return JSON.stringify(this.user)
    };
}

And this is my component: 这是我的组成部分:

user.service.ts user.service.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { User } from './user';


@Injectable()
export class UserService {

public user: User;

constructor(
    private http: Http,
    private headers: Headers = new Headers({'Content-Type': 'application/json'}),
    private requestOptions: RequestOptions = new RequestOptions({headers: headers})) {}

    public init(user: User) {
        this.user = user;
    }
    signup (): Observable<Response> {
        if (this.user.password !== this.user.passwordConfirm) {
      return Observable.throw(new Error('Şifreleriniz uyuşmuyor!'))
        } else {
          return this.http.post('/signup', this.user, this.requestOptions);
        }
    }
}

This is the stack: 这是堆栈:

Error: DI Error
    at NoProviderError.ZoneAwareError (http://localhost:3000/node_modules/zone.js/dist/zone.js:958:33)
    at NoProviderError.BaseError [as constructor] (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:1239:20)
    at NoProviderError.AbstractProviderError [as constructor] (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:1365:20)
    at new NoProviderError (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:1405:20)
    at ReflectiveInjector_._throwOrNull (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:2937:23)
    at ReflectiveInjector_._getByKeyDefault (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:2976:29)
    at ReflectiveInjector_._getByKey (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:2908:29)
    at ReflectiveInjector_.get (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:2777:25)
    at AppModuleInjector.NgModuleInjector.get (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:8491:56)
    at CompiledTemplate.proxyViewClass.AppView.injectorGet (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:11935:49)
    at CompiledTemplate.proxyViewClass.DebugAppView.injectorGet (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:12315:53)
    at ElementInjector.get (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:11790:31)
    at ReflectiveInjector_._getByKeyDefault (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:2973:28)
    at ReflectiveInjector_._getByKey (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:2908:29)
    at ReflectiveInjector_.get (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:2777:25)

If you don't want to use singleton service pattern (means having different instances scoped to component(s) only), you have to put providers:[UserService] in @Component decorator as shown below, 如果你不想使用单件服务模式(意味着只有不同的实例作用于组件),你必须在@Component装饰器中放置providers:[UserService] ,如下所示,

@Component({
    moduleId: module.id,
    selector: 'authentication',

    providers: [UserService]    ///<<<===here

    styles: ['input[type=email].ng-invalid {border: 1px solid #dd0000}'],
    ...
    ...

})

But let's say if you want to have a single instance of your UserService then you have to define it in @NgModule decorator of your root or app component 但是,假设您想要拥有UserService的单个实例,那么您必须在root or app component @NgModule装饰器中定义它。

import { UserService } from './user.service';

@NgModule({
   imports:[...]

   providers:[UserService]      ///<<<===here
   ...
   ...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM