I've refactored an old project (Angular 2) to Angular 6. All works well, besides a problem I have with api calls.
On the sign-in component, when I submit the form, fires a POST request with the data and the interceptor adds certain headers (for now only content-type).
Code on submitting the form:
this.authService.signIn(this.account)
.subscribe( res => {
console.log('RES -> ', res);
this.router.navigate([this.returnUrl]);
},
err => console.log(err));
AuthService methods:
signIn(account: Account) {
const req = new HttpRequest(HttpMethods.Post, AuthService.signInUrl,{account: account});
return this.makeRequest(req);
}
private makeRequest(req: HttpRequest<any>): Observable<any> {
this.progressBarService.availableProgress(true);
return this.http.request(req)
.finally( () => this.progressBarService.availableProgress(false));
}
The console.log I've added is fired twice for some reason: the first time is {type: 0}, and second time returns the data I needed.
I've removed everything from interceptor, leaved only next.handle(req) and it does the same.
Any idea why I receive 2 responses, the first being just {type: 0}?
That's because you using this.http.request(). I guess the first response is actually the response for the OPTIONS request.
If you still insist to use this.http.request(), for example if you using it to upload files, you might need to use rxJs takeLast(1) to get the response that you need.
Here's the reference.
https://angular.io/api/common/http/HttpClient#request
Related
Working on an Angular app (golf handicap generator) and following along with a Pluralsight video to implement a form and using Http and he is using PutsReq as a way to just test the post and response. When I follow everything I am getting the above syntax error but unsure why. All I am trying to do is send 2 different numbers. Here is my code
Service Component
postUserRoundsForm(userRounds: UserHandicapRounds) : Observable<any> {
return this.http.post("https://putsreq.com/ZmOvG1coGYa174oig3r1", userRounds);
}
Template Component
onSubmit(form: NgForm) {
console.log('in onSubmit: ', form.valid)
this.dataService.postUserRoundsForm(this.userHandicapRounds).subscribe({
next: (v) => console.log('Donzo: ', v),
error: (e) => console.log('Errorrr: ', e),
complete: () => console.log('complete: sends NOTHING')
})
}
HTML
<form #handicapCalcForm="ngForm" (ngSubmit)="onSubmit(handicapCalcForm)">
I also checked the network tab in chrome and saw the payload is coming back with the correct data. I also tried re-serving the app and a different browser and that didn't help either.
I'm fairly new to HTTP and trying to learn more about it but haven't been able to find a reason as to why this isn't working, I would think it should
I have an API written in .Net that's being called from a (server-side) JavaScript app. The behavior is very odd and I can't explain.
If I hit the endpoint from Postman - with the same parameters - it works as expected (a MSSQL database is updated), and no errors.
However, when the code below is executed, even though the database is updated, the catch is triggered but - here's the weird part - the err object is {}, just an empty object.
Also, because the err object is empty (not undefined or null), the res.status(...) call triggers another error, obviously because there are no properties on the object.
Any ideas? Thanks in advance.
axios.post('task', formData, { headers: formData.getHeaders() })
.then((result) => {
res.send(result)
})
.catch((err) => {
console.log('#ERROR#')
res.status(err.response.status).send(err.response.data.Message)
})
})
Did you try this?
res.send(result.data)
I hope it will work.
I am new to working with API and I am working on a web-extension to fetch a random quote.
Each time I refresh the page the output works fine with response.data however, I would like to use each object from the responses... and not have the entire data on the page so I can add my custom styles.
I am using Axios + pure js
and I would like to access these values
Can someone please tell me, what I am doing wrong here?
For now, all I can access is request.data
axios
.get(url)
.then(function (response) {
showTextToUser(response.data);
//NOT WORKING console.log(response['verse']);
})
.catch(function (error) {
console.log(error);
});
Here's my request using axios
This is how axios response object look like
{
config:{},
data:{ --PAYLOAD YOU SENT FROM SERVER --},
headers:{},
request:{},
status: // status code,
statusText:''
}
I think you will find the verse object in data object as response.data.verse
I got my json file and I am getting it on the service. Then I am trying to subscribe to it in the component, but in console.log(this.jsonObj) I get empty array. Also if I write console.log(data) - I get json data.
Service :
objUrl = 'assets/jsons/obs.json';
constructor(private http: HttpClient) {
console.log('Hello ObjectsProvider Provider');
}
getObjectsJson() {
return this.http.get(this.objUrl);
}
Component :
jsonObj = {};
this.object.getObjectsJson().subscribe((data =>
this.jsonObj = data
))
console.log(this.jsonObj)
Issue
You are trying to get the Asynchronous data in Synchronous fashion. You are logging the data console.log(this.jsonObj) outside of Observable. So it will get executed without waiting for the result to come from API.
Fix
Just move the log or any code you want to execute the after API inside subscribe. So you your code will look like
jsonObj = [];
this.object.getObjectsJson().subscribe((data =>
this.jsonObj = data;
console.log(this.jsonObj); //<-- data will be appear here.
))
The service method is asynchronous, so the code inside the subscribe() (which makes the assignment) executes at some time in the future, when the http call returns. Your log statement is outside of the subscription, so it happens before the assignment. Try putting the log statement inside the subscription, right after the assignment.
console.log(this.jsonObj) will run before the response of the server. You can work with it as it is. It will run perfectly. you can test it like this
<p *ngIf="jsonObj !== undefined">{{jsonObj.field}}</p>
if you want to check it with console.log, just add it in the subscription like this
this.http.getObjectsJson().subscribe((data => {
this.jsonObj = data
console.log(this.jsonObj)
}));"
I have a loopback 2.x app, in which I have a model Conversation and a model Message, with a relationship "Conversation has many messages". I want to customize the response for POST conversations/:id/messages with a json response different than the default, say {status: 'success'}. I tried to use remote hook for the method __create__messages, but it did not work:
Conversation.afterRemote('__create__messages', function(ctx, next) {
ctx.result.data = {
success: 'yes'
};
next();
});
This still returns the default response. How can I return a custom json for a remote method? I have seen examples only for all models, or for all methods: multiple models, multiple methods
Maybe you can try a version of following code below. Also, I think you are meaning to to manipulate data before the method finishes, not after. If you wait, the response will already be created, preventing your intended goal. Let me know if this works (replace with methods that will work for your use case).
Conversation.observe('before save', function(context, next) {
var instance = context.instance || context.data;
if (!instance) return next();
// Your code here
next();
});