Just started with Angular and attempting to assign the returned json
data to my interface, but it's not working as expected.
Check out the code I'm using below:
- Stackblitz
- Json URL
Just started with Angular and attempting to assign the returned json
data to my interface, but it's not working as expected.
Check out the code I'm using below:
There is no need to use map if your response is an object and you simply want to map the data property from it.
One approach to achieve this would be
getTestData(): Observable<TestObject>{
const url = 'https://api.myjson.com/bins/11x4bx';
// return this.http.get(url).pipe(
// map(response => ((response || {} as any).data || []).map(testData => this.mapTest(testData))));
return this.http.get(url).pipe(
map((resp: any) => {
return <TestObject> {
id: resp.data.id,
view: resp.data.view,
resourceName: resp.data.resourcename,
loadCapacity: resp.data.loadcapacity
}
})
);
}
A cleaner solution would be
getTestData(): Observable<TestObject>{
const url = 'https://api.myjson.com/bins/11x4bx';
return this.http.get(url).pipe(pluck('data'));
}
If you're unsure about how to create a user-friendly interface for your output, consider utilizing JSON2TS
declare module namespace {
export interface Info {
entityTitle: string;
}
export interface Details {
number: string;
category: string;
startDate: string;
endDate: string;
systemID: string;
capacity: string;
userID: string;
resourceID: string;
resourceName: string;
limitationID: string;
selfLeaveRequested: boolean;
bookedForSelf: boolean;
lastModifiedOn: string;
}
export interface MainObject {
info: Info;
details: Details;
}
}
To enhance your code, consider utilizing the map function when dealing with arrays. Your response data currently consists of an object.
getTestData(): Observable<TestObject>{
const url = 'https://api.myjson.com/bins/11x4bx';
return this.http.get(url).pipe(
map((res: any) => {
console.log(res)
return {
id: res.data.id,
view: res.data.view,
resourceName: res.data.resourcename,
loadCapacity: res.data.loadcapacity
} as TestObject
})
);
}
Utilizing map function twice is causing an issue.
The initial map from RxJS is meant for data transformation. However, in this scenario, an Object is being sent through the pipe instead of an array. Hence, there is no necessity to use the second map since it is used to iterate through arrays.
return this.http.get(url).pipe(
map((resp: any) =>
({
id: resp.data.id,
view: resp.data.view,
resourceName: resp.data.resourcename,
loadCapacity: resp.data.loadcapacity
}) as TestObject)
);
}
Your reference:
https://stackblitz.com/edit/angular-httpclient-get-1dg2r2
Just a heads up, opt for a Declarative approach in reactive programming
Wait, what does that mean?
testObject$ = this.http.get(url).pipe(
map((resp: any) =>
({
id: resp.data.id,
view: resp.data.view,
resourceName: resp.data.resourcename,
loadCapacity: resp.data.loadcapacity
}) as TestObject)
);
}
Then within your component you can invoke it using testService.testObject$
I eliminated the method and here's why:
@Deborah Kurata highlighted this in her RxJS course (she is a GDE on Angular)
I am in the process of implementing the material2 sidenav component. My goal is to have a standalone, full-height sidebar that smoothly slides in and out without any interference with the rest of the app layout caused by the sidenav-layout. The desired ou ...
After successfully completing an ASP.NET operation, I want to automatically close the browser window. The following code is executed by a button within an Ajax UpdatePanel: Page.ClientScript.RegisterClientScriptBlock(typeof(LeaveApproval), "ShowSuccess", ...
I am looking to parse data from an Object and save them in an array. Specifically, I aim to extract all the US shoe sizes and compile them into an array. However, when utilizing the filter method, it only retrieves the first item with the "us" value. { ...
Click here to view the image For instance: If I enter a value in the "USED(kl)" textbox, it should subtract that value from the corresponding row where "KILOGRAM/S" is located; Upon clicking the update button, only the specific row should be affected wh ...
I'm fairly new to working with rxjs and I've been struggling to find the right operator for what I want to achieve. Here's my scenario - I have an array that needs to be populated with results from another observable. Once this array has en ...
I'm working on developing a directive that can toggle an element open or closed when a specific link is clicked. The issue I'm facing is that, upon clicking one trigger, all instances are being toggled open instead of just the intended one. If y ...
How can I restrict the width of columns by defining a width attribute on the div.dcolumn DOM element to preserve the layout with overflowing cells? I want the content of any overflowing cell (like the 9px column) to be hidden while maintaining the specifie ...
Before submitting the form, I would like to trigger the html5 geolocation javascript code. Here's how I envision the process: upon form submission, the user is prompted with a geolocation popup. After allowing access, the form data should be processed ...
After countless hours of troubleshooting, I still can't figure out why the code snippet below is not working properly on my website at : <script> $(window).scroll(function () { if ($(window).scrollTop() > 400) { ...
I had installed TypeScript through npm a while back Initially, it was working fine but turned out to be outdated Trying to upgrade it with npm ended up breaking everything. Is there any way to do a fresh installation? Here are the steps I took: Philip Sm ...
I need assistance with validating dynamically created textareas. In the code below, I am able to validate only the first row but struggling to do so for the second row. How can I get all the row values validated? Thank you in advance. To generate dynamic ...
As I attempt to utilize Ajax to retrieve data from my website using a script that should be able to execute from any location, the Ajax code within my script is structured like this: var ajax = new XMLHttpRequest(); ajax.open('GET', 'http:/ ...
While working on a node.js application, I successfully implemented s3 file upload. However, there have been instances when the s3 bucket goes down for maintenance or other reasons. To address this issue and keep users informed, I wanted to incorporate an A ...
Today is the first time I'm reaching out for help rather than figuring things out on my own. I'm currently working on a website layout that consists of visible tiles all with equal sizes, forming a grid structure. The challenge I face is making t ...
I successfully implemented an error page following the documentation provided. https://nuxtjs.org/docs/2.x/concepts/views#error-page To achieve this, I created an error.vue file in the /layouts directory and assigned a custom layout to it. <template&g ...
Looking at the code snippet provided, it appears quite straightforward. The intention is to display an alert labeled "Trigger 2" if the variable "ret" returns a value of "fail". However, there seems to be a glitch with the IF statement causing it to trigge ...
I am new to React and facing difficulties identifying errors in my code. My goal is to display a list of users retrieved from a server using socket.io. Below is the original code snippet: // list of users const [users, setUsers] = useState() useEffect(() ...
Whenever I attempt to submit a post or use the get method from my index.php file which calls Ajax_mysql.php through the Ajax function POST or GET, I encounter a frustrating Internal 500 error. The server doesn't provide any additional information abou ...
I am utilizing v-calendar to display the start date and time as well as end date and time in dateTime mode. My goal is to prevent the end date and time from being set before the start date and time. In order to achieve this, I have implemented the :min-dat ...
This particular issue has been widely recognized and discussed multiple times in various forums. Despite the extensive search, I have not come across satisfactory solutions. var aniApp = angular.module("aniApp", []); aniApp.controller('mainCtrl&ap ...