2017-03-23 30 views
0

您好我正在嘗試使用JSON REST API,但在嘗試刪除元素時遇到問題;當我打電話刪除方法我有這樣的錯誤:在使用TypeScript的Angular組件中未定義的服務

EXCEPTION: Error in ./ClientiComponent class ClientiComponent - inline template:28:16 caused by: this.userService is undefined 

這裏ClientiComponent代碼

import { Component, OnInit, Injectable } from '@angular/core'; 
import { Http, Headers, Response } from '@angular/http'; 
import { User } from 'app/user'; 
import { Observable } from 'rxjs/Rx'; 
import { userService } from './userService' 
import 'rxjs'; 
import 'rxjs/add/operator/toPromise'; 

@Component({ 
selector: 'clienti', 
templateUrl: './clienti.component.html', 
styleUrls: ['./clienti.component.css'] 
}) 
export class ClientiComponent { 
private users = []; 
private userService: userService; 
data: Object; 
loading: boolean; 
selectedUser: User; 
private userUrl = 'http://localhost:3000/users'; 
private headers = new Headers({ 'Content-Type': 'application/json' }); 

constructor(private http: Http) { 
http.get('http://localhost:3000/users') 
    .flatMap((data) => data.json()) 
    .subscribe((data) => { 
    this.users.push(data) 
    }); 
} 


delete(user: User): void { 
alert("error"); 
this.userService 
    .remove(user.id) 
    .then(() => { 

    this.users = this.users.filter(h => h !== user); 
    if (this.selectedUser === user) { this.selectedUser = null; } 
    }); 
} 

如果我把這個刪除方法內ClientiComponent它工作得很好,而是我想弄清楚如何將這種方法在我的userService.ts文件中。

在這裏有從ClientiComponent

remove(id: number): Promise<void> { 
    const url = `${this.userUrl}/${id}`; 
    alert("url"); 
    return this.http.delete(url, {headers: this.headers}) 
     .toPromise() 
     .then(() => null) 
     .catch(this.handleError); 
    } 

稱爲userService方法有什麼錯我的代碼?在構造函數中

回答

0

嘗試導入構造函數內的服務,然後立即檢查。看看下面的代碼

constructor(
     private userService: userService){} 

delete(user: User): void { 
alert("error"); 
this.userService 
    .remove(user.id) 
    .then(() => { 

    this.users = this.users.filter(h => h !== user); 
    if (this.selectedUser === user) { this.selectedUser = null; } 
    }); 
} 
+0

不行的,這是現在的錯誤:'例外:未捕獲的(在承諾):錯誤:DI Error' – Alessandro

+0

你在app.module.ts文件導入,並在供應商包括 – Vignesh

+0

如果我把userService放到提供程序中,我得到這個錯誤'不能實例化循環依賴! userService' – Alessandro

0

進樣的服務您的ClientiComponent,以這樣的方式

constructor(private http: Http, private _userService: UserService) { 
    //your constructor code... 
} 

您可以在official documentation/tutorials閱讀更多關於注射服務和其他服務業(小節:注入HeroService

此外,我建議使用良好的做法和名稱服務使用大寫字母(fe userService在user.service.ts中)

相關問題