Angular 2의 이전 API 요청에서 매개 변수가 필요한 API에서 데이터를 가져 오는 방법은 무엇입니까?

Ellery

API에 연결되는 간단한 Angular 2 애플리케이션을 작성 중입니다. API에는 다음과 같은 엔드 포인트가 있습니다.

/ job / : id

/ client / : id

내 애플리케이션에 다음 데이터가 포함 된 테이블을 표시하고 싶습니다.

직업 이름

업무 설명서

고객 이름

클라이언트 이메일

이 정보를 표시하는 간단한 구성 요소가 있습니다.

import {Component, OnInit} from '@angular/core'
import {JobService} from './job.service'

@Component({
    selector: 'job',
    template: `
    <table>
    <tr>
    <td>Job Name: {{job.name}}</td>
    <td>Job Description: {{job.description}}</td>
    <td>Client Name: {{client.name}}</td>
    <td>Client Email: {{client.email}}</td>
    </tr>
    </table>`,
    providers: [JobService]
})
export class JobComponent{
    job = {};
    client = {};


    constructor(private _jobService: JobService){}

    ngOnInit(){

        this._jobService.getJob(1)
            .subscribe(job => {
                this.job = job;
            });

        this._jobService.getClient(this.job.client_id)
            .subscribe(client => {
                this.client = client;
            });
    }
}

및 다음 서비스

import {Http} from '@angular/http'
import {Injectable} from '@angular/core'


@Injectable()
export class JobService {


    constructor(private _http: Http){
    }

    getJob(id){
        return this._http.get(window.__env.apiUrl + 'job/' + id + '/')
        .map(res => res.json());
    }

    getClient(id){
        return this._http.get(window.__env.apiUrl + 'client/' + id + '/')
        .map(res => res.json());
    }


}

이렇게하면 작업 API 호출의 정보가 테이블에 올바르게 기록되지만 두 API 호출이 동시에 실행되므로 클라이언트 정보에 대한 오류가 반환되므로 시스템이 아직 작업 API 호출에서 client_id를받지 못했습니다. 그래서 Angular에서 첫 번째가 완료된 후이 두 번째 API 호출을 만드는 올바른 방법이 무엇인지 궁금합니다.

참고로 여기에 오류가 있습니다.

예외 : 응답 상태 : 404 Not Found for URL : http : // localhost : 8080 / au / api / client / undefined /

건배

티에프 판

flatMap / mergeMap사용하여 순서대로 실행

ngOnInit(){

    this._jobService.getJob(1)
      .map(res => {
        this.job = job;
        return this.job.client_id;
      })
      .flatMap(client_id => this._jobService.getClient(client_id))
      .subscribe(client => {
          this.client = client;
      });
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관