简体   繁体   中英

When injecting(importing) a service into my constructor I get a "No provider" error

Angular 2 - When injecting(importing) a service into my constructor I get a "No provider" error.

Here's my service I'm importing:

 export class EnvironmentService {

   public baseurl: string = "/baseurl/example/";  

 }

Here's my class with the error:

import {Http, Headers} from "angular2/http";
import {Injectable} from 'angular2/angular2';
import {EnvironmentService} from './environmentService';

@Injectable()

export class AuthService {

    constructor(private _environmentService: EnvironmentService) {

        //This is where the error is.
        console.log(this._environmentService);

    }

    isUserLoggedIn = (): Promise<boolean> => {   

        return new Promise((resolve, reject) => {
           resolve(true);
        })
    }

}

app.module.ts Providers 中添加AuthService

Most likely you didn't specify EnvironmentService as a provider for your application. You can do it by passing all providers in a second argument of the bootstrap function, or using providers and viewProviders properties of the Component decorator:

bootstrap(AppComponent, [EnvironmentService /*, other providers */]);

// or

@Component({
    // ... component config
    providers: [EnvironmentService],
    // or
    viewProviders: [EnvironmentService]
})
class AppComponent { /* ... */ }

GO to the module that you want to use the EnvironmentService ie app.module.ts or other modules.

after imports you will see provider as an array add the EnvironmentService

providers: [AuthService]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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