Angular no provider for NameService

后端 未结 18 1916
遇见更好的自我
遇见更好的自我 2020-11-30 18:44

I\'ve got a problem loading a class into an Angular component. I\'ve been trying to solve it for a long time; I\'ve even tried joining it all in a single file. What I have i

18条回答
  •  星月不相逢
    2020-11-30 19:41

    Angular 2 has changed, here is what the top of your code should look like:

    import {
      ComponentAnnotation as Component,
      ViewAnnotation as View, bootstrap
    } from 'angular2/angular2';
    import {NameService} from "./services/NameService";
    
    @Component({
      selector: 'app',
      appInjector: [NameService]
    })
    

    Also, you may want to use getters and setters in your service:

    export class NameService {
        _names: Array;
        constructor() {
            this._names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];
        }
        get names() {
            return this._names;
        }
    }
    

    Then in your app you can simply do:

    this.names = nameService.names;
    

    I suggest you go to plnkr.co and create a new Angular 2 (ES6) plunk and get it to work in there first. It will set everything up for you. Once it's working there, copy it over to your other environment and triage any issues with that environment.

提交回复
热议问题