Response status check using angularjs - angularjs

I am trying to check response status by using following code:
$scope.coach = Coach.get(function(response) {
if(response.status === 401) {
alert("Coach");
}
});
but its not working, can anyone help please. thanks

$resource.get() takes two callbacks; the second is the error handler and receives the response object:
$scope.coach = Coach.get(
function (coach) {
// ... could do something with returned data object here
},
function (res) {
alert("Coach status: " + res.status);
}
);
Check this plunker for a working example: http://plnkr.co/edit/WHL63r?p=preview

Related

React js Axios Get Request in submit form

i have a simple input form where i put a list of strings , then for each element of the string (string[i]) i run an ajax Get request to my api .
so here is the ajax request :
async function getUsers(props){
try{
const response = await Axios.get(`url=`+props)
console.log(response)
return response;
}catch{
console.log("response failed")
}
}
and i run it here :
... some code here ...
for(var i =0; i < string.length; i++){ // map the entery (string)
getUsers(string[i]).then(res => {
this.setState({
string2:res // this one is just for testing
});
console.log(res.data.id);
mystring22.push({res});
console.log("me inside the promise : " + this.state.string2.data.id);
})
setTimeout(() => {
console.log("iam not empty " + this.state.string2.data.id);
console.log(mystring22);
/* -----------------
I WANT TO DO SOME WORK HERE
-----------------*/
}, 3000);
this.setState({
string3 : mystring22
})
... some code here ...
so everything works fine , and my problem is the following :
the code take too much time (3 second for each request ) , is there is a way to change the code so it can do "SOMETHING" after each request , i tried to delete the setTimeout or reduce it but that not working the array is undefined after that .
hope you can help me .
thank you
setState is an async function, so when you call:
setState({ string2: res });
this.state.string2; // OUTDATED
in order to access the updated value, you must use the callback:
setState({ string2: res },
() => { console.log(this.state.string2) }); // UP TO DATE
as you can see in this codesandbox example, with the callback on line 27 and without the callback on 33.

Angular2 - send object in http.post request body

I am working on Angular2 web project, in my ts class I have an object :
Object: any= {
"first":null,
"second":null,
"third": null,
}
I want to send the object in http.post request body. I tried the next code, but it doesnot work;
method() {
const url='/pathname/';
return this.http.post(url, this.Object).pipe(map((data:any)=>data));
}
I got an error in console:
error : HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK",url: "http://localhost:8080/path", ok: false,..}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for
http://localhost:8080/path 400 OK"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "OK"
url: "http://localhost:8080/path"
Can you explain me how to send typescript object in post request body ? Thank you in advance
You need to subscribe to the post observable returned by method function. It is done like this.
this.method().subscribe(
res => {
// Handle success response here
},
err => {
// Handle error response here
}
);
you should subscribe the post method because this method of http class returns a observable.
you can rewrite your code as:-
method() {
const url='/pathname/';
return this.http.post(url, this.Object).subscribe( resp=> {
const data = resp; // response you get from serve
}, error => {
console.log(error); //error you get from server
});
}
you are getting the 400 bad request error, the payload keys are mis matching with the middle wear. please suggest pass the correct params into Request object.

How does Meteor methods return results?

I am using meteor/react for learning facebook graph api.
I want to access users' post on facebook timeline and display them on screen. How can that be done?
With the guidance of the solution provided here [How to perform common FB actions using Meteor?. I have tried the following code: server.js
Meteor.methods({
'seePost' : function(){
var graph=Npm.require('fbgraph');
if(Meteor.user().services.facebook.accessToken){
graph.setAccessToken(Meteor.user().services.facebook.accessToken);
var future = new Future();
var onComplete = future.resolver();
graph.get('/me/feed',function(err,result) {
console.log(result);
return onComplete(err,result);
})
Future.wait(future);
}
else{
return false;
}
}
});
client side code :
Meteor.call("seePost", function(err,result) {
if(err) console.log("error" , err);
else console.log("RES", result);
});
I expect the result displayed in the client side console since I want to show the users the posts on his/er timeline, But I get following output :
RES, undefined
You can do it using await and Meteor.callAsync
Basically the client code waits for the call to complete, and gives you the returned data
const result = await Meteor.callAsync("seePost");
Errors should be handled with a try..catch block
If you use fibers/future, you need to return something with "future".
const future = new Future();
// some code getting result or something
future.return(something);
return future.wait();
this will return something in the callback from client call.
try this code, when you're using fibers you need to "wait" for the response
Meteor.methods({
'seePost': function () {
var graph = Npm.require('fbgraph');
if (Meteor.user().services.facebook.accessToken) {
graph.setAccessToken(Meteor.user().services.facebook.accessToken);
var future = new Future();
var onComplete = future.resolver();
graph.get('/me/feed', function (err, result) {
console.log(result);
if (err) {
return future.return(false);
} else {
return future.return(result);
}
})
return future.wait();
}
return false;
}
});

React findOne returning undefined on Client

I'm having problems using findOne because it always returns undefined.
This code:
Routine.js
Meteor.methods({
.... // Some lines missing
'routines.getRoutine'(routineId) {
check(routineId, String);
return Routines.findOne(routineId);
},
});
Note: If I do a console.log of Routines.findOne(routineId) it correctly shows the element that i'm looking for.
App.jsx
handleSubmit(event) {
event.preventDefault();
const comment = ReactDOM.findDOMNode(this.refs.comment).value.trim();
Meteor.call('routines.addComment', this.state.routine._id, comment);
let a = Meteor.call('routines.getRoutine', this.state.routine._id);
ReactDOM.findDOMNode(this.refs.comment).value = '';
this.setState({
routine: a,
});
}
In my Appjs doesn't matter how I try 'a' is always undefined, what am I doing wrong?
Thanks for the help in advance!
I'm pretty sure your problem is that Meteor calls on the client are async and so the method you're calling hasn't completed by the time you're querying the same data.
Try putting the rest of the code in the callback like so:
handleSubmit(event) {
event.preventDefault();
const comment = ReactDOM.findDOMNode(this.refs.comment).value.trim();
Meteor.call('routines.addComment', this.state.routine._id, comment, function() {
let a = Meteor.call('routines.getRoutine', this.state.routine._id);
ReactDOM.findDOMNode(this.refs.comment).value = '';
this.setState({
routine: a,
});
});
}

Backbone.js error callback parameters getting replaced with model

I have a RESTful JSON api that I use to perform server-side calls like this:
Servlet.prototype.ajaxJSON = function (jobject, func, context) {
var self = this;
$.getJSON(this.name, jobject, function (json) {
...
}).fail(function(jqXHR, status, errorThrown) {
var callname = JSON.stringify(jobject).slice(1,JSON.stringify(jobject).indexOf(':'));
if(func !== null) {
func(JSON.parse('{' + callname+': {"error": "Server Error:' + errorThrown + '"}}'));
}
});
};
However, when I try to use the error callback in my model:
newComment.save(null, {
'success': _.bind(function(model, response) {
...
}, this),
'error': function(model, error) {
errorAlert(error, 'Could not post comment');
}
});
For some reason, I'm getting a Backbone model for my error parameter. I've stepped through the code and it looks like Backbone has some sort of custom wraperror method that's screwing everything up. Can anyone tell me what is going on here? Thanks!
Figured it out. The problem was with my model.sync method. I had a condition in it to check for an error that looked like:
if(_.isObject(json.post_comment) && json.post_comment.error) {
options.error(model, json.post_comment.error, options);
}
That needed to be:
if(_.isObject(json.post_comment) && json.post_comment.error) {
options.error(json.post_comment.error);
}
Guess I was reading the documentation wrong. :/

Resources