用于在API中获取数据的Angular服务

时间:2017-10-27 12:44:51

标签: angular

我编写了我的第一个Angular App,我希望从本地提供的另一个API Rest获取数据。

我的工作基于Angular tuto巡回英雄。我使用组件服务来调用我的API并将结果返回到另一个组件中。 我不知道如何在Angular中正确调试。我的API Rest正常运行,如果使用我的浏览器调用,则返回数据。

我的组件数据表(显示返回数据API)正确运行并显示HTML但不显示 * ngFor 部分(每个数据的tr表)。

如果您有帮助调试的技巧或找到错误的位置......

app.component.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';
}

app.module.ts

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 { }

应用-routing.module.ts

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 {}

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>

datatable.component.ts

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

operations.service.ts

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

.json()方法会消耗响应的正文,因此除非从API返回,否则您不必调用data

因此,您应该将res.json().data as Operation切换为res.json() as Operation[]