这是我的文件userdata.service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs';
import { map } from "rxjs/operators";
import { catchError } from 'rxjs/operators';
import { Data } from './userdata';
@Injectable()
export class UserDataService {
url : "http://localhost:4200/assets/data/userdata.json";
constructor(private http:Http) { }
getDataWithObservable() : Observable<any>{
return this.http.get(this.url)
.pipe(
map(this.extractData),
catchError(this.handleErrorObservable)
);
}
private extractData(res: Response)
{
let body = res.json();
return body;
}
private handleErrorObservable (error: Response | any)
{
return Observable.throw(error.message || error); …Run Code Online (Sandbox Code Playgroud) HTML:
<div *ngIf="userdata; else blank;">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Role</th>
<th>Gender</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of userdata">
<td>{{data.Id}}</td>
<td>{{data.Name}}</td>
<td>{{data.Email}}</td>
<td>{{data.Address}}</td>
<td>{{data.Role}}</td>
<td>{{data.Gender}}</td>
<td>
<button type="button" (click)="setUser(data)" class="btn btn-default btn-sm edit">
<span class="glyphicon glyphicon-edit"/> Edit</button>
<button type="button" id="close" style="height: 30px;"
(click)="deleteUser(data.Id)" class="btn btn-default btn-sm close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</td>
</tr>
</tbody>
</table>
</div>
<ng-template #blank>No Records found...</ng-template>
Run Code Online (Sandbox Code Playgroud)
这是我在userdata数组中得到的:
[{
"Id": "1",
"Name": "sdfd",
"Email": "fdg",
"Address": "dfg",
"Role": "Admin",
"Gender": "male"
}, { …Run Code Online (Sandbox Code Playgroud) 这是我在book.service.ts中的代码:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs';
import { Book } from './book';
import { map } from "rxjs/operators";
import { catchError } from 'rxjs/operators';
//import { Component, OnInit } from '@angular/core';
//import {HttpClient} from "@angular/common/http";
//import { Observable } from 'rxjs/Observable';
//import 'rxjs/add/operator/map';
//import 'rxjs/add/operators/catch';
//import 'rxjs/operators/toPromise';
@Injectable()
export class BookService
{
url = "http://localhost:4200/assets/data/books.json";
constructor(private http:Http) { }
getBooksWithObservable(): Observable<Book[]>
{
return this.http.get(this.url)
.pipe(map(this.extractData))
.catchError(this.handleErrorObservable);
}
getBooksWithPromise(): …Run Code Online (Sandbox Code Playgroud)