您好我正在嘗試使用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方法有什麼錯我的代碼?在構造函數中
不行的,這是現在的錯誤:'例外:未捕獲的(在承諾):錯誤:DI Error' – Alessandro
你在app.module.ts文件導入,並在供應商包括 – Vignesh
如果我把userService放到提供程序中,我得到這個錯誤'不能實例化循環依賴! userService' – Alessandro