2017-10-27 4 views
0

첫 번째 각도 패키지를 작성하고 다른 API에서 데이터를 가져오고 싶습니다. 나머지는 지역에서 사용할 수 있습니다.API 나머지에서 데이터를 가져 오는 각도 서비스

나의 작품은 Angular tuto tour-of-heroes를 기반으로합니다. 내 API를 호출하고 다른 구성 요소에서 결과를 반환하기 위해 구성 요소 서비스를 사용합니다. Angular에서 어떻게 디버그가 올바르게 수행되는지 모르겠습니다. 내 API 브라우저가 올바르게 호출되어 실행되면 데이터를 반환합니다.

내 구성 요소 datatable (반환 데이터 API 표시)이 올바르게 실행되고 HTML은 표시되지만 * ng의 경우 부분 (각 데이터에 대해 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 { } 

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

도움 주셔서 감사합니다.

+0

흠. 아마도 : res.json(). data as Operation'은'res.json() as Operation []'일 수 있습니다. '.json()'메소드는 응답 본문을 소비하므로 API에서 리턴되지 않는 한'data'를 호출 할 필요가 없습니다. –

+0

차이가 없습니다. 나는 아마도 CORS 문제라고 생각합니다. – darkomen

+0

@ LenilsondeCastro : 제 문제는 2 가지 유형입니다. .data가없는 내 API rest (Symfony) 및 response.json의 cors 구성. 응답을 게시 할 수 있고 이것을 검증 할 수 있습니까? 고맙습니다 – darkomen

답변

1

.json() 메서드는 응답 본문을 사용하므로 API에서 반환하지 않는 한 data을 호출 할 필요가 없습니다.

res.json().data as Operationres.json() as Operation[]으로 전환해야합니다.

관련 문제