Angular 6 Observable Http get async - httpclient

i'm newbie at angular and i have problem with get async data from http client, my code:
User Service:
getAll(): Observable<User[]> {
return this.http.get<User[]>(`${this.API_URL}/users`);
}
registerUser(user: User) {
return this.http.post(`${this.API_URL}/api/auth/registerUser`, user);
}
User model:
export class User {
id: number;
name: string;
username: string;
surname: string;
email: string;
password: string;
street: string;
numberStreet: string;
postalCode: string;
city: string;
}
User-list component:
export class UserListComponent implements OnInit {
public data: User[];
constructor(private userService: UserService, private modalService: NgbModal) {
}
ngOnInit() {
this.getListUsers();
}
getListUsers() {
this.userService.getAll().subscribe(
restItems => {
this.data = restItems;
}
);
}
this.userService.registerUser(this.registerForm.value)
}
and now if i add user and send post in database user is stored, but on front it doesnt come up. After reload page list of users working

Related

Nest.js, Graphql, Typeorm, Postgres mutations

I`m a newbee at this technologies and I literally dont understand how to do task. My task: create 2 tables, for categories and tasks, after that create mutation for creating category and tasks(todos).
mutation {
createTodo(input: {
categoryName: “”,
text: “”
}) {
category: {
id
title
}
id
text
isCompleted
}
}
I created objectTypes and input types, but I dont understand how to create such mutation. Example objectTypes and Inputs
#ObjectType()
export class CategoryType {
#Field(() => ID)
id: number
#Field(() => String)
readonly title: string
}
export interface TodoI {
id: number;
text: string;
isCompleted: boolean;
categoryId: number
category: any;
}
#InputType()
export class CategoryInput {
#Field()
readonly title: string
#Field(() => TodoInput,{nullable: true})
readonly todos: TodoI
}
#ObjectType()
export class TodoType {
#Field(() => ID)
id: number
#Field()
readonly text: string
#Field()
readonly isCompleted: boolean
#Field(() => Int)
readonly categoryId: number
}
#InputType()
export class TodoInput {
#Field()
readonly text: string;
#Field()
readonly isCompleted: boolean;
#Field(() => Int)
readonly categoryId: number;
}

Flutter Ferry Graphql pointing to the Entitiy not the dto

I have an entity is Nestjs
#Entity({ name: 'recipes' })
#ObjectType()
export class Recipe {
#PrimaryGeneratedColumn()
#Field(() => Int)
id: number;
#Column()
#Field()
videoUrl: string;
#Column()
#Field()
description: string;
}
I also have a create recipe dto
#InputType()
export class CreateRecipeInput {
#Field()
videoUrl: string;
#Field()
description: string;
#Field(() => [String])
ingredientNames: string[];
#Field(() => [String])
instructionNames: string[];
}
in my ferry Graphql I have this
mutation CreateRecipe($createRecipeInput: CreateRecipeInput!) {
createRecipe(createRecipeInput: $createRecipeInput) {
videoUrl
description
ingredientNames
}
}
The problem I have is if I get an error in the property ingredientNames, but if I add that property to the Recipe entity it works. It's like Ferry is not following the Recipe Dto. When I look at the schema.graphql is flutter The create recipe Dto is there.
input CreateRecipeInput {
videoUrl: String!
description: String!
ingredientNames: [String!]!
instructionNames: [String!]!
}

Error: Cannot query across many-to-many for property on updating

I am try to update many to may relation.
export class CreateProductDto {
#ApiProperty()
#IsString()
description: string;
#ApiProperty()
#IsString()
name: string;
#ApiProperty({ isArray: true })
#IsNumber({}, { each: true })
#IsArray()
categoryIds: number[];
}
export class UpdateProductDto extends PartialType(CreateProductDto) {}
export class ProductsService {
constructor(
#InjectRepository(Product)
private productRepository: Repository<Product>,
private categoriesService: CategoriesService,
) {}
async update(id: number, updateProductDto: UpdateProductDto) {
let categories: Category[] = undefined;
if (updateProductDto.categoryIds) {
categories = await Promise.all(
updateProductDto.categoryIds.map(
async (id) => await this.categoriesService.findOneOrFail(id),
),
);
delete updateProductDto.categoryIds;
}
await this.productRepository.update(
{ id },
{ ...updateProductDto, categories },
);
return await this.findOneOrFail(id);
}
async findOneOrFail(id: number) {
const product = await this.productRepository.findOne({ id });
if (product) {
return product;
}
throw new BadRequestException(`Product is not present`);
}
}
#Entity()
export class Product extends BaseEntity {
#Column()
description: string;
#Column()
name: string;
#ManyToMany(() => Category, (object) => object.products, {
cascade: true,
eager: true,
})
#JoinTable()
categories: Category[];
}
#Entity()
export class Category extends BaseEntity {
#Column()
name: string;
#ManyToMany(() => Product, (object) => object.categories)
products: Product[];
}
Finally when i try to call ProductsService.update with this payload it
"categoryIds": [ 2 ]
i got an error like this
Error: Cannot query across many-to-many for property categories
Can some please help me to update many to many
In your Category Entity add the relation id of Product and use save method instead of update when you update your entity.
#Entity()
export class Category extends BaseEntity {
#Column()
name: string;
#ManyToMany(() => Product, (object) => object.categories)
products: Product[];
// Add this
#Column()
productId: string;
}
To solve problemes like i use.
async dummyUpdate(objetUpdateDto: ObjectUpdateDto): Promise<TypeReturn> {
const { idObjectToUpdate, colum1ToUpate, colum2ToUpate } = objetUpdateDto;
try {
const objectToUpdate = await this.repositoryOfEntity.findOne(idObjectToUpdate);
idObjectToUpdate.colum1ToUpate = colum1ToUpate;
idObjectToUpdate.colum2ToUpate = colum2ToUpate;
await this.repositoryOfEntity.save(objectToUpdate);
return objectToUpdate,
} catch(err) {
throw new ConflictException("your message" + err);
}
}

How to select data by using typeorm from 3 tables which depend on each other?

I have 3 entity which depend on each other and I have a problem with querying data from them by using one request.
First one User:
#Entity()
export class User {
#PrimaryGeneratedColumn()
id: number;
#Column()
firstName: string;
#Column()
lastName: string;
#Column()
login: string;
#Column()
password: string;
#Column()
ownerId: number;
#OneToOne(() => Role, (role) => role.user)
#JoinColumn()
role?: Role;
}
Second one Role:
#Entity()
export class Role extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
name: string;
#Column()
description: string;
#ManyToOne(() => User, (user) => user.role)
#JoinColumn()
user: User | null;
#ManyToMany(() => Permission, { cascade: true })
#JoinTable({ name: 'roles_has_permissions' })
permissions: Permission[];
}
Third one Permission:
#Entity()
export class Permission {
#PrimaryGeneratedColumn()
id: number;
#Column()
name: PossiblePermissions;
}
How to select data from database. I’m using typeorm with Postgresql and I want to get array like this.
[{
…user info by ownerId
role: {
…role which related this user
permissions: [{
…permissions which related this role
}, …]
}
}, …]
Use query builder https://typeorm.io/#/select-query-builder
In your case it should be something like this:
await connection
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.role", "role")
.leftJoinAndSelect("role.permissions", "permissions")
.getMany()

Typegoose binding referernce to polymorphic model

I have a situation with polymorphic models
interface IEvent {
title: string;
}
class SubscribeEvent implements IEvent {
#prop()
title: string;
#prop({ref: User})
user: IUser;
}
class NewsEvent implements IEvent {
#prop()
title: string;
#prop({ref: Post})
post: IPost;
#prop({ref: User})
user: IUser;
}
class OrderEvent implements IEvent {
#prop()
title: string;
#prop({ref: Order})
order: IOrder;
}
Now I created a typegoose model:
class Card extends Typegoose {
#prop()
name: string;
#prop()
events: IEvent[];
}
How do I correctly map and extract the Card instance with populated references?