简体   繁体   English

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

[英]Undefined service in Angular component using TypeScript

Hi I'm trying to consume a JSON REST API but I have a problem when I try to delete an element; 嗨,我正在尝试使用JSON REST API,但是在尝试删除元素时遇到问题; when I call delete method I have this error: 当我调用delete方法时,出现以下错误:

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

Here ClientiComponent code 这里的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; }
  });
}

If I put the remove method inside ClientiComponent it works fine, but instead I want figure out how to move this method inside my userService.ts file. 如果我将remove方法放在ClientiComponent内,则可以正常工作,但我想弄清楚如何在我的userService.ts文件中移动此方法。

Here there is method in userService called from ClientiComponent 这是从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);
  }

What's wrong with my code? 我的代码有什么问题?

Inject service in constructor your ClientiComponent , in this way: 通过以下方式将服务注入到您的ClientiComponent的构造函数中:

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

You can read more about injection services and others in official documentation/tutorials (subsection: Inject the HeroService ) 您可以在官方文档/教程中了解有关注入服务和其他服务的更多信息(小节: 注入HeroService

Additionally, I suggest to use good practise and name service use capital letters (fe UserService in user.service.ts) 此外,我建议使用良好做法,并使用大写字母命名服务(在user.service.ts中使用UserService)

Try to import the service inside the constructor and check now. 尝试将服务导入构造函数中并立即检查。 see the below code 见下面的代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Angular组件中为服务变量使用typescript getter或local变量 - Using a typescript getter or local variable for a service variable in Angular component 角度服务返回未定义到组件 - Angular service returning undefined to component 带有TypeScript Firebase API的Angular 2返回服务中的对象数组,但未在组件中定义 - Angular 2 w/ TypeScript Firebase API returns array of objects in service but undefined in component Angular Service未命中,函数未定义TypeScript - Angular Service not getting hit, function is undefined TypeScript Angular共享服务-订阅将未定义传递给组件 - Angular Shared Service - Subscribe passes undefined to component Angular 服务变量在组件中出现未定义 - Angular Service Variable comes up as undefined in component 如何修复 Angular 对组件的服务响应 - 未定义 - How to fix Angular Service Response to Component - Undefined 带有Firebase的Angular 5-服务在服务完成之前返回未定义的组件 - Angular 5 with Firebase - Service returns undefined in component before service completes 使用 Angular 在 Typescript 中获取未定义的 object 错误 - Getting undefined object error in Typescript using Angular Angular 8:使用服务创建动态组件。 错误:无法读取未定义的属性“createComponent” - Angular 8: Using service to create dynamic component. Error: Cannot read property 'createComponent' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM