2017-03-23 34 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中)

相关问题