In my generic handler I perform an asynchronous HTTP POST using RestSharp and then display some html to the user before waiting for the POST request to come back. Then once the Http Response comes back I would like to display a message by injecting some Javascript.
var asyncHandle = client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
//here I would like to display a notification to the user but the handler already returned processedHtml at this point
context.Response.Write(#"<script type='text/javascript'>
window.parent.$.gritter.add({
text: 'some message',
time: 20000,
sticky: false
});</script>");
}
});
//this line executes before waiting for response from async call
context.Response.Write(processedHtml);
The problem is that at that point the lifecycle is over so context.Response.Write(#"<script ... ") generates "Object reference not set to instance of an object". Is there any other way to inject javascript when the async response comes back?
Related
In my project i made multiple request to server to get data for single page. I want to make all request asyc. Right now until i get the response from first request,the response of second request is not load.
So basically i just want to achive asyc request and response so one request will not wait for other request to finish.
Right now it's like first come first serve fashion.
But i want from multiple request which request get first response should load first.
this is code of my component
constructor(private _dashboardService: DashboardService) {
this.getLineChart();
this.todayPaymentDetails();
this.todayPaymentMethod();
this.rewardCustomers();
this.getAverageBill();
this.getItemByVolumn();
this.getItemBySales();
}
todayPaymentMethod(id=null){
this.paymentMethodsLoader=0;
this._dashboardService.getTodayPaymentMethod(id).subscribe(res =>{
if(null != res.data && '' != res.data){
this.location = res.data.location;
this.payment_methods = res.data.payment_methods;
}
this.paymentMethodsLoader=1;
});
}
this is my service code:
getTodayTotalPayment(id) : Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.get(environment.apiUrl + constants.API_V1 + 'today-total-payment/'+id, options)
.map(res => res.json())
.catch((error: any) => Observable.throw(error.json().error || error));
}
Here shows code for only one request but as shown in constructor i send multiple request at a time.
FIrst it is not a good practise to call function like this in constructor.
For running multiple request or observable together use operators i.e. switchMap etc.
Follow this video link related to event loop in JavaScript this will improve your JavaScript execution , event loop concepts . also explains how asynchronous code executed.
Hope it will help.
I am transacting .NET API through Angular2(honestly.. 5) I implement server side-model validation using Data Annotations Attributes. As such, the API returns bad request(404) with the validation messages attached:
if (!ModelState.IsValid)
return this.BadRequest(ModelState);
My issue has to do on how to display those messages in my angular view.
My Angular service:
submitForm(formObj: FormDto) {
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json; charset=utf-8');
return this.http.post("/api/Forms", JSON.stringify(formObj), { headers })
.map((res: Response) => console.log(res));
//need a .catch here obviously ??????
}
and the way I call the service from the component itself:
submitForm() {
this.formService.submitForm(this.formObj)
.subscribe(res => { console.log(res);
//update this bit to display error messages ?????
});
}
Again, my issue is how to display properly the returned validation error messages coming from the .NET API.
Let's star with the fact that the modelState is coming as an object(key-value pairs). Thus, you can access the object in view by a specific key. You can have a variable in your component and store the modelState object in it.
To the point....
I wouldn't touch the Angular service at all, but the way you subscribe to it in order to separate success and failed callback:
submitForm() {
this.formService.submitForm(this.formObj)
.subscribe((data) => //do what ever on success,
(err) => { this.errors= err.error; });
}
After that, you are able to see your error messages in the view. Something like:
<span class="error-message">{{errors['EmailAddress']}}</span>
Put the line above to every input it's needed but change the key to view the right message. I've done a quick demo and is working.
I hope that helped.
I am playing with angular 2 and I have problem with sending http get request.
I created method like this:
test(){
console.log("call test");
let header = new Headers();
header.append("authorization",'change9ziKuJH8wnVbNES3AMleYGPKzZ');
this._http.get('http://localhost:42055/api/Question',{headers:header}).do(res => console.log("Result: " + JSON.stringify(res)));
}
The main problem is that, this http request never was send. I look at the Fiddler and there is no request to my localhost:42055.
Unfortunately Angular don't display any errors, so I don't have any clue what is going one.
Observables are lazy so you need to subscribe them to actually execute corresponding processing (HTTP requests in your case):
this._http.get('http://localhost:42055/api/Question',{headers:header})
.do(res => console.log("Result: " + JSON.stringify(res)))
.subscribe((res) => { // <-------------
// handle result
});
As I understand when a request to an event emitter on the server arrives, that request is never closed and you only need to res.write() every time you would like to send a message. However is there a way to be notified when the client that performed this request has left? Is there a property on the request object?
suppose I have the following route
app.get('/event',function(req,res){
//set response headers
//how do I check if req object is still active to send a message and perform other actions?
})
The basic sequence of events should be similar in other frameworks, but this example is Grails 3.3.
First set up endpoints to subscribe, and to close the connection.
def index() {
// handler for GET /api/subscribe
rx.stream { Observer observer ->
// This is the Grails event bus. background tasks,
// services and other controllers can post these
// events, CLIENT_HANGUP, SEND_MSG, which are
// just string constants.
eventBus.subscribe(CLIENT_HANGUP) {String msg ->
// Code to handle when the grails event bus
// posts CLIENT_HANGUP
// Do any side effects here, like update your counter
// Close the SSE connection
observer.onCompleted()
return
}
eventBus.subscribe(SEND_MSG) {String msg ->
// Send a Server Sent Event
observer.onNext(rx.respond(msg))
}
}
}
def disconnecting()
{
// handler for GET /api/disconnect
// Post the CLIENT_HANGUP event to the Grails event bus
notify(CLIENT_HANGUP, 'disconnect')
}
Now in the client, you need to arrange to GET /api/disconnect whenever your use-case requires it. Assuming you want to notice when someone navigates away from your page, you could register a function on window.onbeforeunload. This example is using Vue.js and Axios.
window.onbeforeunload = function (e) {
e.preventDefault()
Vue.$http({
method: 'get',
url: 'http://localhost:8080/api/disconnect'
})
.then((response) => { console.log(response) })
.catch(({error}) => { console.log(error) })
}
In the case of Servlet stacks like Grails, I found that I needed to do this even if I had no housekeeping of my own to do when the browser went away. Without it, page reloads were causing IOExceptions on the back end.
I'm trying out Node.js by writing a very basic http/web caching proxy, and have hit something I haven't managed to break through.
Assuming I have a very basic proxy functionality (listen to request, pipe it to external server, wait for response, pipe it back to client), how do I detect when the client (web browser) cancels the request? When the user clicks "Stop"/Esc on his browser, the browser doesn't send me any "request" or info and attaching a callback for when the "response" connection ends doesn't get called.
Here's what I mean:
http.createServer (clientRequest, clientResponse) {
var client = http.createClient (port, hostname);
var request = client.request (method, url, headers);
request.addListener ('response', function(response){
response.addListener ('data', function(chunk){
// forward data to clientResponse..
}
response.addListener ('end', function(){
// end clientResponse..
}
});
clientResponse.addListener('end', function(){
// this never gets called :(
// I want it to terminate the request/response created just above
}
}
Turns out I should be binding to the "close" event instead of the "end" event of the request.
That does actually make sense.
I'm posting this here for anyone else who might encounter the same issue:
clientResponse.addListener('close', function(){
// this gets called when the user terminates his request
}