Editing Received Object After Angular HTTP Request - javascript

In a project I am working on, after obtaining a list of objects from an HTTP "get" request, one of the fields for each object is a string containing a status, "DEAD", "IDLE", etc. Is there any way to edit the structure of the object that comes in the list so it contains a few more fields based on that status value? For example, after the transformation each of the objects in the list would have the boolean fields isDead, isIdle, etc. Is this what the transformResponse() method in Angular does?

You can do something like this.
private getData(): void {
this.http.get('https://reqres.in/api/users?page=2').pipe(map((res: any) => {
return res.data;
})).subscribe((data) => {
this.data =data.map((item) => {
return {
id: item.id,
first_name: item.first_name,
last_name: item.last_name,
avatar: item.avatar,
age: 50
}
});
});
};
In here UI am requesting for a list of data and for each of the items in the list I am appending a age attribute.
You can find a working example in here

Related

How to access id from this httpresponse in angular to perform edit and delete actions based on id

In the screenshot showing list of applications created
function to get list of apps -> ts file
getcmsApps() {
this.getCmsService.getApps().subscribe((res: any) => {
this.data = res;
console.log(res)
})
}
editAppById(appid: string): void {
}
deleteAppId(appid: string){
}
The response you get is an object array. So you can just loop trough the array and access the field by its key name
let AngularResponse = [
{
createdon: "4/1/2022",
division: "test",
email: "aaaa#gmail.com",
fax: "1",
hrbinformation: "1",
id: "d7ab1fc0-0e33-4fb7-ac71-1bf48ddd8bf8"
},
{
createdon: "6/2/2022",
division: "test",
email: "bbbbbb#gmail.com",
fax: "2",
hrbinformation: "2",
id: "a869fdd8-bf99-49d9-bb72-7bb11e6fadbf"
},
]
console.log(AngularResponse[0].id);
//OR to get all of them
AngularResponse.forEach(arrayItem => console.log(arrayItem.id))
Usually the httpService will return an Observable on which you can subscribe in the subscription part you can perform all sorts of operations based on the response you got.
I have to take a look at you code to give you further informations but what I can suggest to do is the following
request = // your http request observable from httpService
request.subscribe((response) => {
// retrieve the id from the response object (as I can see in the
// screenshot your response is an array so you will probably have to loop
// through it)
});
Another option to consider would be to use RxJs operators to make operations on the response object (eventually using the tap operator) before the subscription part.

Vuejs return data from component to Laravel

I am trying to make a search bar to collect a list of products which the user will then be able to select an array of products and add it to an order.
So far the products can be searched, added to a "products" array via an "add" button and they are able to see the data within products. They are also able to remove products that they do not want.
My issue is that I am trying to send the data from the "products" array with a parent form. The search component is located within the form as well as the list. But I do not know how I would send the array with the form.
I do not need to send the entire product object, but just the ID which will be used to link up the products with the order.
Here is where the component is:
<div class="uk-margin" id="search">
<label for="Search" class="uk-form-label">Search products to add</label>
<search input="ess"></search>
</div>
Here is the vuejs component data:
export default {
data() {
return {
keywords: null,
results: [],
products: []
};
},
watch: {
keywords (after, before) {
this.fetch();
}
},
methods: {
fetch() {
axios.get('/search', { params: { keywords: this.keywords } })
.then(response => this.results = response.data)
.catch(error => {});
},
addProduct (product) {
let duplicate = false;
this.products.forEach((item, index) => {
if (item.ID === product.ID) {
duplicate = true;
}
});
if (!duplicate) {
this.products.push(product);
}
},
removeProduct (product) {
Vue.delete(this.products, product);
}
}
}
Everything works fine, but my question is.. How am I able to pass the data back to the html / laravel to use it while sending data to the controller. I only need to send the "products" array, I have tried using input with the data but it isn't working. Does anyone know how I could do it, or is the best way to do so, using JavaScript and add them to an array by finding all the elements which are being displayed?
Many thanks.

using prisma, how do you access newly created record from within a nested write (update first, then create within)

Using Prisma, I have a question about accessing a record that was newly created from within a nested write (update first, then create within).
I'm following along the examples on this page in the prisma docs.
In particular, I am looking at the following two items in the data model:
Note, I have slightly modified the example for the purposes of this question by adding a counter to User.
model User {
id Int #id #default(autoincrement())
email String #unique
posts Post[]
counter Int
}
model Post {
id Int #id #default(autoincrement())
title String
author User? #relation(fields: [authorId], references: [id])
authorId Int?
}
Now, let's say you want to create a new Post and connect it to the User and at the same time, you also want to increment the counter.
My assumption, after reading this section of the doc is that you would need to update the existing User and within that, create a new Post record.
i.e.
const user = await prisma.user.update({
where: { email: 'alice#prisma.io' },
data: {
// increment the counter for this User
counter: {
increment: 1,
},
// create the new Post for this User
posts: {
create: { title: 'Hello World' },
},
},
})
My question is this. In the above scenario, how do you access the newly created Post in the return of the query?
In particular, say you want to get the id of the new Post?
From what I can tell, the returned user object could possibly include the array of all associated Posts, i.e. if you added this to the update query...
include: {
posts: true,
}
But I can't yet see how, using Prisma, you get the individual Post that you just created as part of this update query.
I have found one way of achieving this that works.
It uses the tranaction api.
Basically, instead of trying to use a nested write that begins with an update on User and contains a nested create on Post...
I split the two operations out into separate variables and run them together using a prisma.$transaction() as follows.
const updateUser = prisma.user.update({
where: { email: 'alice#prisma.io' },
data: {
// increment the counter for this User
counter: {
increment: 1,
},
},
});
const createPost = prisma.post.create({
data: {
// create the new Post for this User
title: 'Hello World',
author: {
connect: {
email: 'alice#prisma.io',
},
},
},
});
const [ updateUserResult, createPostResult ] = await prisma.$transaction([updateUser, createPost ]);
// if createPostResult, then can access details of the new post from here...

createList does not pick up relationship in Mirage js

I am trying to create multiple posts that belong to a user using Mirage js createList facility. I have created models with corresponding relationships:
models: {
user: Model.extend({
posts: hasMany(),
}),
post: Model.extend({
user: belongsTo()
})
}
In the seeds method, I am trying to create a list of posts and allocate them to a user with this code:
seeds(server) {
let posts = server.createList("post", 2);
server.create("user", {
name: "John",
posts: [posts],
});
}
Unfortunately when I hit this.get("/users"); in http request I receive a mirage error, which I understand but can't fix:
Mirage: You're trying to create a user model and you passed in "model:post(1),model:post(2)" under the posts key, but that key is a HasMany relationship. You must pass in a Collection, PolymorphicCollection, array of Models, or null.
As far as I can tell I am passing an array of Models? How can I fix it, please?
So the problem was:
posts: [posts]
This part returns an array (or collection) already:
let posts = server.createList("post", 2);
So wrapping it in another array [post] is incorrect.
Using server.create("...") we can hook onto it by putting it in array, but server.createList is already returning an array.
Correct syntax is:
seeds(server) {
let posts = server.createList("post", 2);
server.create("user", {
name: "John",
posts: posts,
});
}
or even shorter:
seeds(server) {
let posts = server.createList("post", 2);
server.create("user", {
name: "John",
posts,
});
}

How to extend/modify the object in nodejs api?

i am using the angular-fullstack yeoman generator. created a schema for a Product, and a set of api crud operations. all works well. now in the get list operations, i don't want to receive all the fields, only a subset. like a select in sql. i would also wish to alter one value. instead of the price, i need price * 1.1 .
how to do that?
here is the code for the index method (returns list of products):
// Gets a list of Products
export function index(req, res) {
Product.findAsync()
.then(respondWithResult(res))
.catch(handleError(res));
}
function respondWithResult(res, statusCode) {
statusCode = statusCode || 200;
return function(entity) {
if (entity) {
res.status(statusCode).json(entity);
}
};
}
As stated in the documentation, .find() takes two params, query and projection.
// params
Product.findAsync(query, projection)
You can use projection to "select" a subset of fields;
// example
Product.findAsync({}, { _id: 1, name: 1, description: 1 })
// result, only the three specified field will be returned
[
{ _id: 'abc123', name: 'Some name', description: 'Some description'},
{...}
]
If you want to manipulate data I think you have to use the aggregation pipeline

Categories

Resources