如何同步Angular2 http get?
How to synchronise Angular2 http get?
我了解使用 observable 我可以在请求完成时执行一个方法,但是我如何才能等到 http get 完成并且 return 在 ng2 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;
}
"value" 将在 returned 时为空,因为 get 是异步的。
您不应尝试使 http 调用同步运行。从来都不是一个好主意。
在您的 getAllUser
实现中,它应该 return 一个来自函数的可观察对象,并且调用代码应该订阅而不是您在方法本身内部创建订阅。
类似
getAllUser(): Observable<UserDTO> {
return this.http.get("MY_URL")
.map(res => res.json());
}
在你的调用代码中,你应该订阅并做任何你想做的事情。
如你所见,第一个回调等待来自请求的数据和
在那里你可以继续你的逻辑(或使用第三个)
示例:
.. subscribe( data => {
this.value = data;
doSomeOperation;
},
error => console.log(error),
() => {console.log("Completed");
or do operations here..;
}
});
请找到您的问题的代码
下面是组件和服务 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;
}
}
}
By looking at the angular source (https://github.com/angular/angular/blob/master/packages/http/src/backends/xhr_backend.ts#L46),很明显,XMLHttpRequest 的异步属性没有被使用。 XMLHttpRequest的第三个参数需要设置为"false"用于同步请求
如何使用 $.ajax(of jQuery) 或 XMLHttpRequest.
它可以作为asynchornize使用。
你的服务class:/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
}
}
另一种解决方案是实施排序优先级队列。
据我了解,在您添加订阅者之前,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
}>
您必须决定如何将元素添加到数组中。最后,后台会发生以下情况:
// HttpPriorityQueue#processQueue() called at a set interval to automatically process queue entries
processQueue
方法会做这样的事情:
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);
});
}
如果您能够添加新的依赖项,您可以尝试使用以下 NPM 包:async-priority-queue
我看了看,但找不到任何方法来使 HTTP 调用同步而不是异步。
所以解决这个问题的唯一方法是:将您的调用包装在带有标志的 while 循环中。在该标志具有 "continue" 值之前不要让代码继续。
伪代码如下:
let letsContinue = false;
//Call your Async Function
this.myAsyncFunc().subscribe(data => {
letsContinue = true;
};
while (!letsContinue) {
console.log('... log flooding.. while we wait..a setimeout might be better');
}
我了解使用 observable 我可以在请求完成时执行一个方法,但是我如何才能等到 http get 完成并且 return 在 ng2 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;
}
"value" 将在 returned 时为空,因为 get 是异步的。
您不应尝试使 http 调用同步运行。从来都不是一个好主意。
在您的 getAllUser
实现中,它应该 return 一个来自函数的可观察对象,并且调用代码应该订阅而不是您在方法本身内部创建订阅。
类似
getAllUser(): Observable<UserDTO> {
return this.http.get("MY_URL")
.map(res => res.json());
}
在你的调用代码中,你应该订阅并做任何你想做的事情。
如你所见,第一个回调等待来自请求的数据和 在那里你可以继续你的逻辑(或使用第三个)
示例:
.. subscribe( data => {
this.value = data;
doSomeOperation;
},
error => console.log(error),
() => {console.log("Completed");
or do operations here..;
}
});
请找到您的问题的代码 下面是组件和服务 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;
}
}
}
如何使用 $.ajax(of jQuery) 或 XMLHttpRequest.
它可以作为asynchornize使用。
你的服务class:/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
}
}
另一种解决方案是实施排序优先级队列。
据我了解,在您添加订阅者之前,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
}>
您必须决定如何将元素添加到数组中。最后,后台会发生以下情况:
// HttpPriorityQueue#processQueue() called at a set interval to automatically process queue entries
processQueue
方法会做这样的事情:
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);
});
}
如果您能够添加新的依赖项,您可以尝试使用以下 NPM 包:async-priority-queue
我看了看,但找不到任何方法来使 HTTP 调用同步而不是异步。
所以解决这个问题的唯一方法是:将您的调用包装在带有标志的 while 循环中。在该标志具有 "continue" 值之前不要让代码继续。
伪代码如下:
let letsContinue = false;
//Call your Async Function
this.myAsyncFunc().subscribe(data => {
letsContinue = true;
};
while (!letsContinue) {
console.log('... log flooding.. while we wait..a setimeout might be better');
}