2015-10-23 21 views
16

私はobservableを使って理解するリクエストが完了したらメソッドを実行できますが、http getが完了するまで待ってからng2 httpでレスポンスを返します。 GETは非同期であるため、その戻ったときAngular2 httpを同期させる方法

getAllUser(): Array<UserDTO> { 
    this.value = new Array<UserDTO>(); 
    this.http.get("MY_URL") 
        .map(res => res.json()) 
        .subscribe(
         data => this.value = data, 
         err => console.log(err), 
         () => console.log("Completed") 
    ); 

    return this.value; 
} 

「値」意志がnullで..

+1

あなたはこれが唯一のように、この質問への答えではありません – Vineet

+0

@Vineet角度2は、 '$ q' – Targaryen

答えて

-6

httpコールを同期して動作させないでください。決して良い考えではありません。

getAllUser実装では、関数からオブザーバブルを返す必要があり、メソッド自体の内部でサブスクリプションを作成する代わりに、呼び出しコードがサブスクライブする必要があります。

あなたがコードを呼び出すには

getAllUser(): Observable<UserDTO> { 
     return this.http.get("MY_URL") 
         .map(res => res.json()); 
} 

のようなもの、あなたが購読してあなたがやりたいはずです。

+24

この回答は質問の代替実施を提供しており、私は回答に感謝します。しかし、これは質問に答えません。同期HTTPリクエストを作成する方法はありませんか?私は同じ質問への答えを探しています。私は応答を得るまでブラウザをブロックすることでOKです(実際にはそれを望みます)。 – inki

+2

この回答はsync xhrを使用しないことを示唆しているだけで、質問のユースケースの理由を説明したり、質問に答えたりすることはありません。 –

+0

角度ソースを見ると、XMLHttpRequestの非同期属性が使用されていないようです。 – Suresh

-1

Javascriptがシングルスレッド、それが応答を待っている間全体のブラウザをブロックする同期HTTPリクエストを行っています。 これとは異なるアーキテクチャを検討してください。

+23

使用していない' $のq'サービスを使用するか、AJAXの成功コールバックで、あなたの関数を実行しますか、コメントに含めるべきuggestion。 –

-3

あなたが見るように、リクエストとそこ からのデータを待って最初のコールバック、あなたのロジックで上に行く(または第三いずれかを使用)することができます

例:

.. subscribe(data => { 
       this.value = data; 
       doSomeOperation; 
       }, 
       error => console.log(error), 
      () => {console.log("Completed"); 
         or do operations here..; 
        } 
}); 
+0

「do operations here ...」の場所に他の購読リクエストを入力できますか? – GSeriousB

0

のコードを検索してくださいあなたの問題以下 は、コンポーネントとサービスfile.Andコードではsynchornize

以下
import { Component, OnInit } from '@angular/core'; 
import { LoginserviceService } from '../loginservice.service'; 

@Component({ 
    selector: 'app-login', 
    templateUrl: './login.component.html', 
    styleUrls: ['./login.component.css'] 
}) 
export class LoginComponent implements OnInit { 
    model:any={}; 
    constructor(private service : LoginserviceService) { 
} 

ngOnInit() { 

} 
save() { 
    this.service.callService(this.model.userName,this.model.passWord). 
    subscribe(
     success => { 
     if(success) { 
      console.log("login Successfully done---------------------------- -"); 
      this.model.success = "Login Successfully done"; 
    }}, 
    error => console.log("login did not work!") 
); 
} 

} 

のために正常に動作しているサービスファイル..です

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import { UserData } from './UserData'; 
import 'rxjs/add/operator/map' 
import 'rxjs/add/operator/toPromise' 
import {Observable} from 'rxjs/Rx' 

@Injectable() 
    export class LoginserviceService { 
    userData = new UserData('',''); 
    constructor(private http:Http) { } 

    callService(username:string,passwrod:string):Observable<boolean> { 
    var flag : boolean;  
    return (this.http.get('http://localhost:4200/data.json'). 
     map(response => response.json())). 
     map(data => { 
      this.userData = data; 
      return this.loginAuthentication(username,passwrod); 
     }); 
     } 

    loginAuthentication(username:string,passwrod:string):boolean{ 
    if(username==this.userData.username && passwrod==this.userData.password){ 
     console.log("Authentication successfully") 
     return true; 
    }else{ 
    return false; 
    } 


    } 
} 
2

enter image description here角度ソース(https://github.com/angular/angular/blob/master/packages/http/src/backends/xhr_backend.ts#L46)を見ることによって、XMLHttpRequestを非同期の属性が慣れていないことは明らかです。同期要求の場合、XMLHttpRequestの3番目のパラメータを "false"に設定する必要があります。

+1

ほとんどのブラウザでは、同期要求はサポートされなくなりました。より良いUIエクスペリエンスのために... – sancelot

-1

$ .ajax(of jQuery)またはXMLHttpRequestの使い方はどうですか?

asynchornizeとして使用できます。

+0

jQueryを角で使用しないでください – Targaryen

+0

私はそうは思わない。 –

+0

あなたはどうしてそう思いますか? 一部のプログラマーはjQueryをAngularで優先的に使用しています。 –

2

あなたのサービスクラス:/project/app/services/sampleservice.ts

@Injectable() 
    export class SampleService { 

     constructor(private http: Http) { 
     } 

     private createAuthorizationHeader() { 
     return new Headers({'Authorization': 'Basic ZXBossffDFC++=='}); 
     } 


     getAll(): Observable<any[]> { 
     const url=''; 
     const active = 'status/active'; 
     const header = { headers: this.createAuthorizationHeader() }; 
     return this.http.get(url + active, header) 
      .map(
      res => { 
       return res.json(); 
      }); 
     } 

    } 

コンポーネント:/project/app/components/samplecomponent.ts

export class SampleComponent implements OnInit { 


    constructor(private sampleservice: SampleService) { 
    } 

    ngOnInit() { 
    this.dataset(); 
    } 

    dataset(){ 
    this.sampleservice.getAll().subscribe(
     (res) => { 
     // map Your response with model class 
     // do Stuff Here or create method 
     this.create(res); 
     }, 
     (err) => { } 
    ); 
    } 
    create(data){ 
    // do Your Stuff Here 
    } 

} 
+0

これまでのレスポンスの変更時には、自動的にメソッドと更新が呼び出されます新しい要素で –

0

別の解決策は、になりますソートの優先度キューを実装します。

あなたが加入者を追加するまで、HTTPリクエストは実行されないと私は理解しています。

Observable<Response> observable = http.get("/api/path", new RequestOptions({})); 

requestPriorityQueue.add(HttpPriorityQueue.PRIORITY_HIGHEST, observable, 
       successResponse => { /* Handle code */ }, 
       errorResponse => { /* Handle error */ }); 

これはrequestPriorityQueueは、あなたのコンポーネントに注入されたサービスであることを前提としています。そのため、あなたはこのような何かを行うことができます。優先キューは、配列内のエントリを次の形式で格納します。

Array<{ 
    observable: Observable<Response>, 
    successCallback: Function, 
    errorCallback: Function 
}> 

要素を配列に追加する方法を決定する必要があります。最後に、次のようにバックグラウンドで発生します:あなたは、次のNPMパッケージを使用してみてください可能性があり、新たな依存関係を追加することができるならば

protected processQueue() { 
    if (this.queueIsBusy()) { 
     return; 
    } 

    let entry: {} = getNextEntry(); 
    let observable: Observable<Response> = entry.observable; 

    this.setQueueToBusy(); // Sets queue to busy and triggers an internal request timeout counter. 
    observable.subscribe() 
     .map(response => { 
      this.setQueueToReady(); 
      entry.successCallback(response); 
     }) 
     .catch(error => { 
      this.setQueueToReady(); 
      entry.errorCallback(error); 
     }); 
} 

// HttpPriorityQueue#processQueue() called at a set interval to automatically process queue entries 

processQueue方法は、このような何かをするだろう。 async-priority-queue

関連する問題