2016-12-22 1 views
1

파이프로 ID를 확인합니다.서비스가있는 파이프에서 ID를 확인하십시오.

나는 서비스/api를 매번 호출하는 것이 최선의 방법이라고 생각하지 않습니까?

전에 모든 국가를 저장하는 것이 더 좋습니까? 파이프 안에서 국가 이름을 어떻게 반환 할 수 있습니까?

서비스 :

getCountry(id:number) { 
    return this._http.get(this.apiUrl + "/country/" + id).map(res => res.json()); 
} 

파이프 :

export class ResolvePipe implements PipeTransform { 
    constructor(public _formDataService: FormDataService) {} 
    transform(value: number, args: any[]): any { 
    this._formDataService.getCountry(value).subscribe(
     data => console.log(data[0].name) 
    ) 
    } 
} 

편집 :

<tr (click)="showProfile(customer)" *ngFor="let customer of (customers | search:term)"> 
    <td>...</td><td>{{customer.country_id | resolve | async}}</td> 
</tr> 

답변

1

먼저 당신이 Observable를 반환해야합니다. 전화 할 때 subscribe()Subscription가 반환됩니다. 또한 실제로 따라서 transform()에서 뭔가를 반환하는 데 필요한 return

export class ResolvePipe implements PipeTransform { 
    constructor(public _formDataService: FormDataService) {} 
    transform(value: number, args: any[]): any { 
    // added `return` and changed `subscribe` to `map` 
    return this._formDataService.getCountry(value).map(
     data => { 
     console.log(data[0].name); 
     return data; // with `{ }` explicit `return` is required 
     }); 
    ) 
    } 
} 

는 다음 반환 된 Observable

<div>{{someId | myIdPipe | async}}</div> 

또는

같은
<some-comp [idProp]="someId | myIdPipe | async></some-comp> 

async 파이프 구독을 파이프를 사용할 수 있습니다 추가 transform에서 가져 와서 결과 값을 바인딩에 사용합니다.

+0

감사합니다. 작동하지만 매우 느립니다. 성능 향상을 위해 무엇을 할 수 있습니까? – robert

+1

천천히 여기에서 말하기 어렵다. 서버의 응답 시간이 오래 걸리나요? 파이프가 너무 자주 실행되어 응용 프로그램 속도가 느려집니다. 나는 여기에서 말할 수 없다. http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-2- 페이지에서 논의 된 것처럼 'FormDataService'내에 캐시를 유지할 수 있습니다. http-network-call-in –

+0

네, 약 1000 번이라고합니다. 캐시가이 문제를 해결해야합니다. – robert

관련 문제