用于在API rest中获取数据的Angular服务
我写了我的第一个Angular应用程序,我想从本地可用的另一个API Rest获取数据 我的作品基于《英雄之旅》。我使用组件服务来调用API,并在另一个组件中返回结果。 我不知道如何在Angular中正确调试。如果使用我的浏览器调用,我的API Rest将正确运行并返回数据 My component datatable(显示返回数据API)正确运行并显示HTML,但不显示*ngFor部分(每个数据的tr表) 如果您有一个技巧来帮助调试或查找错误所在 应用程序组件.ts用于在API rest中获取数据的Angular服务,angular,Angular,我写了我的第一个Angular应用程序,我想从本地可用的另一个API Rest获取数据 我的作品基于《英雄之旅》。我使用组件服务来调用API,并在另一个组件中返回结果。 我不知道如何在Angular中正确调试。如果使用我的浏览器调用,我的API Rest将正确运行并返回数据 My component datatable(显示返回数据API)正确运行并显示HTML,但不显示*ngFor部分(每个数据的tr表) 如果您有一个技巧来帮助调试或查找错误所在 应用程序组件.ts import {Compo
import {Component} from '@angular/core';
@Component({
selector: 'app-my-app',
template: `
<h1>fzfzefzfzefz</h1>
<nav>
</nav>
<app-my-datatable></app-my-datatable>
<!--<router-outlet></router-outlet>-->
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'blablabla';
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {Router, RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
import { DatatableComponent } from './datatable.component';
import { OperationService } from './operation.service';
import { AppRoutingModule } from './app-routing.module';
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [AppComponent, DatatableComponent],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpModule,
RouterModule.forRoot([{path: 'datatable', component: DatatableComponent}])
],
providers: [
OperationService
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {DatatableComponent} from './datatable.component';
const routes: Routes = [
{ path: '', redirectTo: '/datatable', pathMatch: 'full' },
{ path: 'datatable', component: DatatableComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
import { Component, OnInit } from '@angular/core';
import { Operation } from './operation';
import { OperationService } from './operation.service';
@Component({
selector: 'app-my-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit{
title = 'app toto';
operations: Operation[];
constructor(private operationService: OperationService) { }
getOperations(): void {
this.operationService.getOperations().then(operations => this.operations = operations);
}
ngOnInit(): void {
this.getOperations();
}
}
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Operation } from './operation';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class OperationService
{
private headers = new Headers({'Content-Type': 'application/json'});
private operationsUrl = 'http://60.60.60.100/api/operations';
constructor(private http: Http) { }
getOperations(): Promise<Operation[]>
{
return this.http.get(this.operationsUrl)
.toPromise()
.then(response => response.json().data as Operation[])
.catch(this.handleError);
}
getOperation(id: number): Promise<Operation>
{
const url = `${this.operationsUrl}/${id}`;
return this.http.get(url)
.toPromise()
.then(response => response.json().data as Operation)
.catch(this.handleError);
}
update(operation: Operation): Promise<Operation>
{
const url = `${this.operationsUrl}/${operation.id}`;
return this.http
.put(url, JSON.stringify(operation), {headers: this.headers})
.toPromise()
.then(() => operation)
.catch(this.handleError);
}
create(name: string): Promise<Operation>
{
return this.http
.post(this.operationsUrl, JSON.stringify({name: name}), {headers: this.headers})
.toPromise()
.then(res => res.json().data as Operation)
.catch(this.handleError);
}
delete(id: number): Promise<void>
{
const url = `${this.operationsUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
应用程序路由.module.ts
import {Component} from '@angular/core';
@Component({
selector: 'app-my-app',
template: `
<h1>fzfzefzfzefz</h1>
<nav>
</nav>
<app-my-datatable></app-my-datatable>
<!--<router-outlet></router-outlet>-->
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'blablabla';
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {Router, RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
import { DatatableComponent } from './datatable.component';
import { OperationService } from './operation.service';
import { AppRoutingModule } from './app-routing.module';
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [AppComponent, DatatableComponent],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpModule,
RouterModule.forRoot([{path: 'datatable', component: DatatableComponent}])
],
providers: [
OperationService
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {DatatableComponent} from './datatable.component';
const routes: Routes = [
{ path: '', redirectTo: '/datatable', pathMatch: 'full' },
{ path: 'datatable', component: DatatableComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
import { Component, OnInit } from '@angular/core';
import { Operation } from './operation';
import { OperationService } from './operation.service';
@Component({
selector: 'app-my-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit{
title = 'app toto';
operations: Operation[];
constructor(private operationService: OperationService) { }
getOperations(): void {
this.operationService.getOperations().then(operations => this.operations = operations);
}
ngOnInit(): void {
this.getOperations();
}
}
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Operation } from './operation';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class OperationService
{
private headers = new Headers({'Content-Type': 'application/json'});
private operationsUrl = 'http://60.60.60.100/api/operations';
constructor(private http: Http) { }
getOperations(): Promise<Operation[]>
{
return this.http.get(this.operationsUrl)
.toPromise()
.then(response => response.json().data as Operation[])
.catch(this.handleError);
}
getOperation(id: number): Promise<Operation>
{
const url = `${this.operationsUrl}/${id}`;
return this.http.get(url)
.toPromise()
.then(response => response.json().data as Operation)
.catch(this.handleError);
}
update(operation: Operation): Promise<Operation>
{
const url = `${this.operationsUrl}/${operation.id}`;
return this.http
.put(url, JSON.stringify(operation), {headers: this.headers})
.toPromise()
.then(() => operation)
.catch(this.handleError);
}
create(name: string): Promise<Operation>
{
return this.http
.post(this.operationsUrl, JSON.stringify({name: name}), {headers: this.headers})
.toPromise()
.then(res => res.json().data as Operation)
.catch(this.handleError);
}
delete(id: number): Promise<void>
{
const url = `${this.operationsUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
datatable.component.html
<h1>efzefzefz</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Label</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let operation of operations">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
操作.服务.ts
import {Component} from '@angular/core';
@Component({
selector: 'app-my-app',
template: `
<h1>fzfzefzfzefz</h1>
<nav>
</nav>
<app-my-datatable></app-my-datatable>
<!--<router-outlet></router-outlet>-->
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'blablabla';
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {Router, RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
import { DatatableComponent } from './datatable.component';
import { OperationService } from './operation.service';
import { AppRoutingModule } from './app-routing.module';
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [AppComponent, DatatableComponent],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpModule,
RouterModule.forRoot([{path: 'datatable', component: DatatableComponent}])
],
providers: [
OperationService
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {DatatableComponent} from './datatable.component';
const routes: Routes = [
{ path: '', redirectTo: '/datatable', pathMatch: 'full' },
{ path: 'datatable', component: DatatableComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
import { Component, OnInit } from '@angular/core';
import { Operation } from './operation';
import { OperationService } from './operation.service';
@Component({
selector: 'app-my-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit{
title = 'app toto';
operations: Operation[];
constructor(private operationService: OperationService) { }
getOperations(): void {
this.operationService.getOperations().then(operations => this.operations = operations);
}
ngOnInit(): void {
this.getOperations();
}
}
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Operation } from './operation';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class OperationService
{
private headers = new Headers({'Content-Type': 'application/json'});
private operationsUrl = 'http://60.60.60.100/api/operations';
constructor(private http: Http) { }
getOperations(): Promise<Operation[]>
{
return this.http.get(this.operationsUrl)
.toPromise()
.then(response => response.json().data as Operation[])
.catch(this.handleError);
}
getOperation(id: number): Promise<Operation>
{
const url = `${this.operationsUrl}/${id}`;
return this.http.get(url)
.toPromise()
.then(response => response.json().data as Operation)
.catch(this.handleError);
}
update(operation: Operation): Promise<Operation>
{
const url = `${this.operationsUrl}/${operation.id}`;
return this.http
.put(url, JSON.stringify(operation), {headers: this.headers})
.toPromise()
.then(() => operation)
.catch(this.handleError);
}
create(name: string): Promise<Operation>
{
return this.http
.post(this.operationsUrl, JSON.stringify({name: name}), {headers: this.headers})
.toPromise()
.then(res => res.json().data as Operation)
.catch(this.handleError);
}
delete(id: number): Promise<void>
{
const url = `${this.operationsUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
从'@angular/core'导入{Injectable};
从'@angular/Http'导入{Headers,Http};
从“./Operation”导入{Operation};
导入“rxjs/add/operator/toPromise”;
@可注射()
导出类操作服务
{
私有头=新头({'Content-Type':'application/json'});
私人运营URL=http://60.60.60.100/api/operations';
构造函数(私有http:http){}
getOperations():承诺
{
返回this.http.get(this.operationsUrl)
.toPromise()
.then(response=>response.json().data作为操作[])
.接住(这个.把手错误);
}
getOperation(id:number):承诺
{
常量url=`${this.operationsUrl}/${id}`;
返回此.http.get(url)
.toPromise()
.then(response=>response.json().data作为操作)
.接住(这个.把手错误);
}
更新(操作:操作):承诺
{
常量url=`${this.operationsUrl}/${operation.id}`;
返回此文件。http
.put(url,JSON.stringify(操作),{headers:this.headers})
.toPromise()
.然后(()=>操作)
.接住(这个.把手错误);
}
创建(名称:string):承诺
{
返回此文件。http
.post(this.operationsUrl,JSON.stringify({name:name}),{headers:this.headers})
.toPromise()
.then(res=>res.json().data作为操作)
.接住(这个.把手错误);
}
删除(id:编号):承诺
{
常量url=`${this.operationsUrl}/${id}`;
返回this.http.delete(url,{headers:this.headers})
.toPromise()
。然后(()=>null)
.接住(这个.把手错误);
}
私有句柄错误(错误:任意):承诺{
console.error('发生错误',error);//仅用于演示目的
返回承诺。拒绝(error.message | | error);
}
}
感谢您的帮助。方法.json()
因此,您应该将res.json().data as Operation
切换为res.json()as Operation[]
Hmm。也许这是:res.json().data as Operation
可以是:res.json()as Operation[]
。.json()
方法消耗响应的主体,因此您不必调用数据,除非它是从API返回的。没有区别。我想可能是CORS的问题…@LenilsondeCastro:我的问题有两种类型。我的API rest(Symfony)和response.json中没有.data的cors配置。你能给我一个回复,我验证一下。非常感谢。