Injection services in Angular2 component not working

I am trying to create an Angular starter kit, but I have problems introducing the service into the component.

Here is my main file app.ts:

/// <reference path="../typings/angular2/angular2.d.ts" />
import 'zone.js';
import 'reflect-metadata';
import 'es6-shim';

import {Component, View, bootstrap} from 'angular2/angular2';
import { MyService } from './services/sampleService';

@Component({
  selector: 'my-app',
  bindings: [MyService]
})
@View({
  template: `
    <ul>
      <li>{{ appStatus }}</li>
      <li>{{ message }}</li>
    </ul>
  `
})
class MyAppComponent {
  appStatus: string;
  message: string;

  constructor(myService: MyService) {
    this.message = myService.getMessage();
    this.appStatus = 'Application is working.';
  }
}

bootstrap(MyAppComponent);

And my service:

import { Injectable } from 'angular2/angular2';

@Injectable()
export class MyService {
  message: string;

  constructor() {
    this.message = "Services are working";
  }

  getMessage() {
    return this.message;
  }

}

As I understand it (from viewing other Angular2 samples), this is the way to go; however, the second I add myService: MyServiceand its use in MyAppComponent, the application does not load. There is no error during the execution of the error, and no errors during compilation.

I also tried removing @Injectablefrom the class MyService, but that didn't make any difference. It still does not load. I had no problem injecting components into the view, so at least this works.

Any ideas?

+4
source share

Source: https://habr.com/ru/post/1610431/


All Articles