2016-06-21 14 views
0

お客様が注文したすべての注文を取得したいと考えています。 私のコンポーネントでは、以下のように書いています。Angular2でsubscribeを使用する方法

ngOnInit() { 
    this.customerId = this.getCustomer(); 
    this.orderHistoryItems = this.getOrders(); 
} 

getCustomer(): string { 
    this._accountService.getCustomer() 
     .subscribe((response) => { 
      if (response.GeneralStatus.toString() === 'Success') { 
       return response.Result.CustomerId; 
      } 
     }); 
    return ""; 
} 

getOrders(): OrderHistory[] { 

    this._trackOrdersService.getOrders(this.customerId) 
     .subscribe((response) => { 
      if (response.GeneralStatus.toString() === 'Success') { 
       return response.Result; 
      } 
     }); 
    return []; 
} 

私はundefinedとして得意先取得しています初めて、これを呼び出します。コントロールは、上記のgetCustomer()メソッドのsubscribeにif条件を入力していません。 同じページをリロードすると、customerIdとordersも取得します。私はgetCustomergetOrdersのそれぞれのhttpコールを以下のように記述しました。

getOrders(custId) { 
    return this._http.get(`${this.apiUrl}GetOrders?CustomerID=${custId}`, { headers: this.headers }) 
     .retry(2) 
     .map(function (res) { 
      return res.json(); 
     }); 
} 

getCustomer(): Observable<ApiResponse<Customer, string>> { 
    return this._http.get('${this.apiUrl}LoggedInCustomer', { headers: this.headers }) 
     .retry(2) 
     .map((response) => response.json()) 
     .catch(this.handleError); 
} 

上記のコードに間違いがある場合は、私を助けてください。

答えて

0

subscribe呼び出しで結果を返そうとしていると思いますが、これはインライン関数を使用しているため機能しません。

方法は再びObservableを返却するか、あるいは、このようなコールバックを渡すために、次のようになります。

ngOnInit() { 
    this.getCustomer((id) => { 
     this.customerId = id; 
    }); 

    this.getOrders((orderItems) => { 
     this.orderHistoryItems = orderItems; 
    }); 
} 

getCustomer(callback: (id) => void) { 
    this._accountService.getCustomer() 
     .subscribe((response) => { 
      if (response.GeneralStatus.toString() === 'Success') { 
       callback(response.Result.CustomerId); 
      } 
     }); 
} 

getOrders(callback: (orderItmes: OrderHistory[]) => void) { 

    this._trackOrdersService.getOrders(this.customerId) 
     .subscribe((response) => { 
      if (response.GeneralStatus.toString() === 'Success') { 
       callback(response.Result); 
      } 
     }); 
} 
+0

は返事をありがとうございました。私は購読から値を返すためにこれを試してみます。あなたはまた、初めての理由を教えてもらえますか?私はcustomerIdを ""としています(つまり、条件が満たされていればコントロールが上手くいかないので、間違った注文をフェッチしようとしています)。getOrdersコールが実行を完了した後、 ifcontent id getCustomer()とcustomerIdを取得します。 –

+0

これはObservableの動作方法ではありません。私のアプローチではもう問題はありません。 – rinukkusu

関連する問題