如何在组件类中实现方法来服务类

时间:2017-03-08 16:48:34

标签: angular typescript

import { Component, OnInit } from '@angular/core';
import {CoursesService} from '../courses.service';

@Component({
  selector: 'app-courses',
  template:`
  <h2>Courses</h2>
  <input type="text" appAutoGrow />
  <ul>
    <li *ngFor="let course of courses">
      {{course }}
    </li>
  </ul>
  <input type="text" #newcourse />
  <button (click)="addCourses(newcourse.value)" >Add</button>
  `,
  providers: [CoursesService]
})

export class CoursesComponent implements OnInit {
  courses;
   addCourses(newcourse: string){
     if(newcourse){          
     this.courses.push(newcourse);
     }
   }
  constructor(coursesService: CoursesService) { 
    this.courses = coursesService.getCourses();
  }
  ngOnInit() {
  }
}

这将正常工作,将元素添加到courses数组中并将其作为LI元素显示在HTML上,但我应该怎么做才能将它实现到服务类(addCourses函数)我尝试多次使用不同的代码实现它但失败了。

这是我的服务类代码

import { Injectable } from '@angular/core';
@Injectable()
export class CoursesService {
    getCourses() {
        return ["course1", "course2", "course3"];
    }
  constructor() { }
}

1 个答案:

答案 0 :(得分:0)

你做这样的事情:

    import { Injectable } from '@angular/core';
    @Injectable()
    export class CoursesService {
        courses = ["course1", "course2", "course3"];
       addCourses(newcourse: string){
         this.courses.push(newcourse);
       }
        getCourses() {
            return this.courses;
        }
      constructor() { }
    }

export class CoursesComponent implements OnInit {
  courses;
   addCourses(newcourse: string){
     if(newcourse){          
       this.coursesService.addCourses(newcourse);
     }
   }
  constructor(private coursesService: CoursesService) { }
  ngOnInit() {
     this.courses = this.coursesService.getCourses();
  }
}