将服务注入到无法正常工作的组件中

时间:2016-06-30 18:47:38

标签: angularjs angular

我是angular2的新手,我正在开发一个简单的应用程序,我想在组件中调用服务方法 GetAuthors(),但不知怎的,我的服务方法< / strong> GetAuthors()没有打电话。我也在服务中使用@Injectable()。组件中的一切都运行良好,并在浏览器中显示结果,但不是service部分,我不知道问题是什么以及我错过了什么,请帮帮我。

这是我的代码

app.component.ts

import { Component } from '@angular/core';
import {AuthorComponent} from './author.component';

@Component({
 selector: 'my-app',
 template: '<h1>Hello Angular!</h1><authors></authors>',
 directives:[AuthorComponent]
})
export class AppComponent { }

author.component.ts

import {Component} from '@angular/core'
import {AuthorService} from './author.service'

@Component({
 selector:"authors",
 template:`
 <h2>Author</h2>
 <p>{{ title }}</p>
 <ul>
   <li *ngFor="#author of authors">{{ author }}</li>
 </ul>
 `,
 })

export class AuthorComponent {
  title = 'This is title for Author Component';
  authors;
  constructor(authorServie : AuthorService){
    this.authors = authorServie.GetAuthors();
  }
}

这是我的服务 的 author.service.ts

@Injectable()
export class AuthorService {
  GetAuthors() : string[] {
   return ["Author 1", "Author 2", "Author 3"];
  }    
}

2 个答案:

答案 0 :(得分:2)

尝试在您的组件中提供服务

import {Component} from '@angular/core'
import {AuthorService} from './author.service'

@Component({
 selector:"authors",
 providers: [AuthorService],
 template:`
 <h2>Author</h2>
 <p>{{ title }}</p>
 <ul>
   <li *ngFor="#author of authors">{{ author }}</li>
 </ul>
 `,
 })

export class AuthorComponent {
  title = 'This is title for Author Component';
  authors;
  constructor(authorServie : AuthorService){
    this.authors = authorServie.GetAuthors();
  }
}

答案 1 :(得分:2)

要在您的组件中使用您的服务,您必须将服务标记为 injectable 并将其添加到组件提供程序中。

来自Angular文档:

  

@Injectable()标记一个类可用于注入器   实例。一般来说,注射器会报告错误   在尝试实例化未标记为的类时   @Injectable()。

我建议您查看有关Angular`s Dependency injection的文章。

<强> author.service.ts

@Injectable() // <- Mark your service as injectable
export class AuthorService {
   GetAuthors() : string[] {
      return ["Author 1", "Author 2", "Author 3"];
   }    
}

<强> author.component.ts

import {Component} from '@angular/core'
import {AuthorService} from './author.service'

@Component({
 selector:"authors",
 providers: [ AuthorService ], // <- Add your services here
 template:`
    <h2>Author</h2>
    <p>{{ title }}</p>
    <ul>
       <li *ngFor="#author of authors">{{ author }}</li>
    </ul>
 `,
 })

export class AuthorComponent {
  title = 'This is title for Author Component';
  authors;
  constructor(authorServie : AuthorService){
    this.authors = authorServie.GetAuthors();
  }
}

如果您有任何其他问题,请告诉我。 欢呼声。