Hey there, I'm currently working on interacting with a JSON REST API and have run into an issue when trying to delete an element. Whenever I call the delete method, I encounter this error:
EXCEPTION: Error in ./ClientiComponent class ClientiComponent - inline template:28:16 caused by: this.userService is undefined
Below is the code for my 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; }
});
}
In my code, if I place the remove method within ClientiComponent it works fine, but I am looking for a way to move this method into my userService.ts file instead.
Here is the remove method in userService that is called from 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);
}
Can anyone help me figure out what's wrong with my code?