2017-03-08 21 views
0
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() { 
    } 
} 

這將正常工作,給元素添加到課程陣列和在HTML爲LI元素顯示,但我應該怎樣做才能落實到服務類(addCourses函數)我嘗試多次用不同的代碼實現它,但失敗了。如何實現方法在組件類服務類

,這裏是我的服務類代碼

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

回答

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(); 
    } 
} 
+0

我已經嘗試過這一個,但錯誤日誌self.context.addcourse不是一個函數... – Steveeeeee

+0

您在構造函數中忘記了'private'關鍵字,請參閱更新 –

+1

謝謝,bro。但是你的代碼仍然有一個小問題,在將ngOnInit()中的代碼更改爲構造函數後,代碼開始工作。 – Steveeeeee