使用TypeScript在Angular组件中使用未定义的服务

时间:2017-03-23 11:45:03

标签: angular typescript

您好我尝试使用JSON REST API但是当我尝试删除元素时遇到问题;当我调用delete方法时,我有这个错误:

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; }
  });
}

如果我将remove方法放在ClientiComponent中,它可以正常工作,但我想知道如何在我的userService.ts文件中移动此方法。

这里有来自ClientiComponent

的userService中的方法
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);
  }

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:1)

尝试在构造函数中导入服务并立即检查。见下面的代码

 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; }
  });
}

答案 1 :(得分:0)

以这种方式在 ClientiComponent 的构造函数中注入服务:

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

您可以在official documentation/tutorials中阅读有关注射服务和其他内容的更多信息(小节:注入HeroService

此外,我建议使用良好做法和名称服务使用大写字母(f.e. UserService in user.service.ts)