I've been working on creating a simple Angular component following a tutorial I found. The component fetches data from an angular-in-memory-web-api using a service called UserService. I have also added an input form for creating new users. The issue arises when I click the add button, as the response received from UserService doesn't allow me to add a new User with name and address (please correct me if I'm mistaken), thus preventing the data from being passed back to the HTML file. Any suggestions on how to fix this? Your advice would be greatly appreciated.
user.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { User } from './user';
@Injectable()
export class UserService {
private usersUrl = 'api/users';
private headers = new Headers({'Content-Type': 'application/json'});
private options = new RequestOptions({ headers: this.headers });
constructor(private http: Http) { }
getUsers(): Observable<User[]> {
return this.http.get(this.usersUrl)
.map(response => response.json().data as User[])
.catch(this.handleError);
}
addUser(user: User): Observable<string> {
return this.http.post(this.usersUrl,
JSON.stringify({ name: user.name,
address: user.address
}),
this.options)
.map(res => res.json().data as User)
.catch(this.handleError);
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
window.alert(errMsg);
return Observable.throw(errMsg);
}
}
home.component.ts
import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { User } from '../user';
import { UserService } from '../user.service';
@Component({
selector: 'app-home',
templateUrl: 'home.component.html'
})
export class HomeComponent implements OnInit {
user: any ={};
users: User[];
constructor(
private userService: UserService,
private http: Http
) {
}
getUsers(): void {
this.userService.getUsers().subscribe(users => this.users = users);
}
add(user: User) {
this.userService.addUser(this.user)
.subscribe(
user => {
this.users.push(user);
console.log(JSON.stringify(user))
}
);
console.log(this.user);
}
ngOnInit(): void {
this.getUsers();
}
}
home.component.html
<form name="form" #f="ngForm" (ngSubmit)="add()">
<input type="text" name="userName" [(ngModel)]="user.name"
#name="ngModel" />
<input type="text" name="userAddress" [(ngModel)]="user.address"
#address="ngModel" />
<button id="addbutton" type="submit"> Add </button>
</form>
<div>
<h2>Data</h2>
<div *ngFor="let user of users">
<input [(ngModel)]="user.name"/>
<input [(ngModel)]="user.address"/>
</div>
</div>