Angular Http get method difference between getById and getByName - json

I am learning the basics of Angular and am currently working on making a REST service using the HttpClient from #angular/common/http.
In many tutorials the first step is making a http.get() call. Usually first the whole list following a http.get() call focused on retrieving only one element. In my example, I have a userList (with users). I have made two methods: getUserById() and getUserByName(). ${this.userUrl} refers to the location of the database (using a JSON file) Below they are displayed:
constructor(private http: HttpClient) {
}
getUserById(id: number): Observable<IUser> {
return this.http.get<IUser>(`${this.userUrl}/${id}`);
}
getUserByName(name: string): Observable<IUser> {
return this.http.get<IUser>(`${this.userUrl}/?name=${name}`);
}
Initially I tried to make the getUserByName() method work via the same way the getUserById(). Thus using:
getUserByName(name: string): Observable<IUser> {
return this.http.get<IUser>(`${this.userUrl}/${name}`);
}
This didn't work and I received the error statement 404 file not found. This is the json file that I worked with (I have set up a json server so that I could also perform http.delete() methods and so on):
{"users": [
{
"id": 1,
"name": "James",
"lastName": "Jameson",
"dateOfBirth": "10-10-2000",
"occupation": "Student"
},
{
"id": 3,
"name": "Steven",
"lastName": "Stevenson",
"dateOfBirth": "10-10-1990",
"occupation": "Police officer"
}]}
Can anyone explain me why the getUserById methods works using just '/${id}' in the url call and why the getUserByName needs to use '?/name=${name}'?

if you use:
getUserById(id: number): Observable<IUser> {
return this.http.get<IUser>(`${this.userUrl}/${id}`);
}
getUserByName(name: string): Observable<IUser> {
return this.http.get<IUser>(`${this.userUrl}/${name}`);
}
and call for exemple /user3262578, it will enter to the first endpoint method which is getUserById(id), you're clearly have ambiguity here. the both methode have the same endpoints.
try to change the second endpoint (getUserByName) to other link like:
return this.http.get<IUser>(`${this.userUrl}/search/${name}`);

This is nothing to do with Angular, this is purely a backend endpoint issue.
Test requests to your backend using an HTTP Rest Client such as PostMan.
Once everything is working at the backend as expected, then integrate with Angular.

Related

Can I create record in Ember without the record name

My Backend Rails API consumes POST requests in the form of
{
"name": "Mark White",
"email" : "mark#xyz.com"
}
Have tried this in Postman and this creates a record successfully.
In my ember frontend, Im using the following code to create a new record, from a form input:
app/routes/addUser.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
addUser(){
let formData = {
"name": this.controller.get('name'),
"email": this.controller.get('email')
};
let newUser = this.store.createRecord('user',formData);
newUser.save();
}
}
});
which generates the request as
{
"user": {
"name": "Mark White",
"email" : "mark#xyz.com"
}
}
which my backend is not prepared to handle and throws an error.
Any way I can quickly conform to the json format that works for me in Postman.
When the question is along the lines with the "How can I change my payload to server for it to be in a certain format?" then you should have a look at customizing a serializer.
But it looks like for solving your problem you might wanna take the standard JSON Serializer; in your app/serializers/application.js just type the following:
import JSONSerializer from '#ember-data/serializer/json';
export default class ApplicationSerializer extends JSONSerializer {
// ...
}
Note that it's for the Ember.js v4, according to your example you're using a bit older version so just adjust the syntax accordingly.

Design Automation LogTrace onProgress cannot match arguments in custom call

I am trying to export a .sat file to one in .stp format. I've had trouble doing the export directly to a bucket (from .ipt to .stp no problem but it doesn't work from .sat to .stp).
Finally, I have tried using LogTrace with custom data to send the file data through a string (step format has string content and it's created correctly). Unfortunately, I can't make work the callback !ACESAPI:acesHttpOperation with the custom data (it does work by default).
This is my workitem call
{
"activityId": "DNhofWmrTzDm5Cdj3ISk0yvVA0IOBEja.InventorActivity16+3",
"arguments": {
"InventorDoc": {
"url": "https://developer.api.autodesk.com/oss/v2/signedresources/xxxxxxxx-aa45-43fa-8c0e-e594a3f671cc?region=US"
},
"InventorParams": {
"url": "data:application/json,{\"height\":\"16 in\", \"width\":\"10 in\"}"
},
"onProgress": {
"verb": "post",
"url": "https://xxxxxxx"
}
}
And this is a part of the log response
I think there is a problem with the API call from !ACESAPI:acesHttpOperation.
I follow same instructions from
callback documentation
Thanks in advance

Is there any documentation for EasyPost that shows the raw JSON for the requests, including headers? Or e.g. a PostMan collection?

I'm just doing the preparation for an integration with EasyPost's Shipping API, which will be server side C#, but we always build a PostMan collection for new integrations, so that we can test data separately from the application if there's an issue.
While I do love the fact that EP provide C# libraries and examples, I'm struggling to find anything that just gives me a list of required headers and the raw JSON format for the body of any requests. It feels a bit like they're just being a little too helpful.
I'll be looking at the Orders endpoint probably.
I've got an account, I've checked all their documentation and searched the internet but haven't found anything so I'm hoping I'm not the first developer to want to use a client application for testing outside my code.
Update:
EasyPost now does have a public workspace https://www.postman.com/easypost-api
with at least 1 public collection
The curl examples are basically the same as json:
For the Address creation example:
-d "address[street1]=417 MONTGOMERY ST"
is the equivalent of
{ "address": { "street1": "417 MONTGOMERY ST" } }
(you might have to escape some characters to be valid json).
Check out How to stimulate cURL request to a request using postman for postman with HTTP Basic Auth.
EasyPost does not provide a public Postman collection; however, here is an example of a shipment Postman body (raw) that could be used. You can adjust the values, actions, objects, etc to your needs.
Using the following, you shouldn't need to pass any headers. You'll pass your API key under the username field with the Basic Auth authorization type.
{
"shipment": {
"to_address": {
"id": "adr_123..."
},
"from_address": {
"id": "adr_123..."
},
"parcel": {
"id": "prcl_123..."
},
"carrier_accounts": {
"id": "ca_123..."
},
"options": {
"address_validation_level": "0"
}
},
"format": "json",
"controller": "shipments",
"action": "create"
}

Unable to post data via HTTP POST in angular 2 on local development server

i am new to web development and trying to get my first app working using Angular 2. I have a reactive form from which i am building a sample invoice which has header and items information. When i try to post the data to store in DB hosted on another machine within the same network, i am getting some error on Observable operator Map stating "[Exception: TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context. at Function.remoteFunction (<anonymous>:2:14)]/
Here is the code :
for simplicity, i have created a variable sampleInvoice with a preformatted JSON structure that is acceptable to the server.
I have tried this data to be posted using REST extension for Chrome and it works fine.
invoice.service.ts
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import 'rxjs/add/operator/delay';
import { Http, Headers, RequestOptions,Response, RequestMethod} from '#angular/http';
import { Invoice, invoices } from './invoice';
createInvoice(invoice: Invoice): Observable <Invoice>{
let sampleInvoice = {
"invoiceDate":"2017-03-21",
"mobileNumber": 8297088993,
"salesPerson": "Ramesh",
"paymentMode": "CASH",
"numOfItems": 1,
"grossAmount": "2100.00",
"totalDiscount": "200.00",
"totalTax":"100.00",
"netAmount": "2000.00",
"paidAmount": "2000.00",
"items": [
{
"lineItem": 1,
"productBarcode": "product1",
"quantity": 1,
"itemGrossAmount":"1200.00",
"itemDiscount": "50.00",
"itemTax":"50.00",
"itemNetAmount":"1200.00"
},
{
"lineItem": 2,
"productBarcode": "product2",
"quantity": 2,
"itemGrossAmount":"400.00",
"itemDiscount": "50.00",
"itemTax":"50.00",
"itemNetAmount":"800.00"
}
]
}
let headers = new Headers({"Content-Type": "application/json"});
console.log(headers);
console.log(JSON.stringify(sampleInvoice));
return this.http.post("http://192.168.0.9:8000/api/invoice/create/",JSON.stringify(sampleInvoice),{headers})
.map(res => res.json());
}
Note: the server (django and mySQL) is hosted on another computer at the mentioned URL.
Any help to resolve this is highly appreciated.
Regards,
navin
the issue turned out to be with the way i wrote Observable. What i had missed is that i did not subscribe to the response but instead used catch operator on response. Since there was no subscription, the Observable was marked as Cold and was not making any network request. here is the updated code snippet of createInvoice
return this.http.post(this.invoiceUrl+"create/",bodyString,options)
.map((res:Response) => res.json())
.subscribe((res)=>{
if (res){
console.log(res);
return res
}});

Can I use normal (rails default) JSON response on Ember Data?

I'm working on a project using Ember/Ember-Data and there is a related/already existing service which is provide API with JSON response.
My project must interact with that service, but the response from that API is someting like below:
{ "id": 39402, "name": "My Name" }
or
[ {"id": 38492, "name": "Other Name" } ]
there is no person: or persons: that is required by Ember-Data compatable response.
How can I using this response on Ember-Data without change on the service or without build API gateway?
Ember-Data uses DS.RestAdapter, which in turn uses DS.RESTSerializer which extends from DS.JSONSerializer for serializing, extracting and massaging data that comes in from the server.
Since in your case you already have the data in your payload, all you need to do for reading the data is override extract method in the JSONSerializer which is actually quite simple.
If you are using ember-cli (which you should :)), your person.js file located inside your app/serializers directory would look as follows.
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extract: function(store, primaryType, payload) {
return payload;
}
});
If you are not using ember-cli, you can do the following:
App.PersonSerializer = DS.JSONSerializer.extend({
extract: function(store, primaryType, payload) {
return payload;
}
});