In Angular2, I have a JSON that returns Customer
Here is my Customer class:
export class Customer {
customerNo: string;
tckn: string;
vkn: string;
customerType: string;
address: Address[];
phone: Phone[];
}
and here is my Address class:
export class Address {
addressType: string;
tradeName: string;
taxOfficeName: string;
taxNo: string;
addressName: string;
addressString: string;
building: string;
floor: string;
apartment: string;
city: string;
county: string;
zipCode: string;
addressDirection: string;
department: string;
indx:string;
}
And here is my json in my customer.service.ts;
getCustomerInfo(): any {
return [{
customerNo: '4767584',
tckn: '968796',
customerType: '1',
address: [{
addressName: '1.address',
addressType: '1',
city: '34',
taxNo: '111'
},
{
addressName: '2.address',
addressType: '2',
city: '6',
apartment: 'test aprt'
}
]
}];
}
I append that json to my model in customer.component.ts
this.model = this._customerService.getCustomerInfo()[0] as Customer;
now I log this._customerService.getCustomerInfo()[0] as Customer;
and I see that json is ok.
now, log this.model the 1st address get values of 2nd address
do you have any idea why this is happening?
Related
I created an Angular project where I'm receiving an object with the following structure from the backend:
{
status: "ok",
totalResults: 12,
articles: [
{
source: {
id: null,
name: "Sports Illustrated"
},
author: "Albert Breer",
title: "Some Title",
description: "Some description",
urlToImage: "http://google.ch/someImage.jpg"
}
]
}
I then tried to create an interface which corresponds to this object. Yet I struggled to define properties that refer to an object resp. an array of objects (e.g. article).
In my first attempt I tried to define my object inline:
export interface Noticias {
status: string;
totalResults: number;
articles: Array<{
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
}>
}
Then I tried to define the properties as duplicates:
export interface Noticias {
status: string;
totalResults: number;
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
articles: Array<{
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
}>
}
Visual Studio Code keeps showing me errors, therefore I doubt whether my approach is correct. Any help would be greatly appreciated!
Based on the json-structure on your first screenshot you'd rather create three separate interfaces: One for Noticias, one for Article and one for Source. Then Noticias contains an array of type Article and Article contains an object of type Source;
noticias.model.ts:
import { Article } from './article.model';
export interface Noticias {
status: string;
totalResults: number;
articles: Article[];
}
article.model.ts:
import { Source } from './source.model';
export interface Article {
source: Source;
author: string;
title: string;
description: string;
urlToImage: string;
}
source.model.ts:
export interface Source {
id: string;
name: string;
}
import { GraphQLString, GraphQLScalarType } from 'graphql'
import { city } from '../../Entities/Cities'
export const CREATE_CITY = {
type: Citytype,
args: {
Name: { type: GraphQLString },
CountryCode: { type: GraphQLString },
District: { type: GraphQLString },
Info: { type: GraphQLString }
},
resolve(parent: any, args: any) {
const { Name, CountryCode, District, Info } = args;
city.insert({ Name, CountryCode, District, Info });
return args;
},
}`
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
#Entity()
export class city extends BaseEntity{
#PrimaryGeneratedColumn()
Id!: number;
#Column({ type: "char", length: 35 })
Name!: string;
#Column({ type: "char", length: 3 })
CountryCode!: string;
#Column({ type: "char", length: 20 })
District!: string;
#Column({ type: "string" })
Info!: string;
}
<I'm trying to learn graphql and I'm a day in>
The Info type is suppose to be a json, in my database it looks like {"Population": 127800} with the same definition. I'm fully aware that it isn't a string/GraphQLString but I don't know how to obtain the value of this object. It returns Info: null and an error - "message": "String cannot represent value: { Population: 127800 }" for obvious reasons.
The code has the same structure as the tutorial I watched and only this video.
Link: https://www.youtube.com/watch?v=fov5e6XJgwc&ab_channel=PedroTech
Q: I want to know how to get the population ex. {"Population": 127800} when I query
it should look like Info: {"Population": 127800}
Optional: How to get the value of population if it looks like - Info: 127800
I made a relationship between two tables that it has: Users and Tasks.
according to the Typeorm ducommentation
Models:
#Entity('tasks')
class Tasks {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
#Column({
type: 'varchar',
})
status: tasksStatus;
#ManyToOne(() => User, user => user.tasks)
user: User;
#Column()
description: string;
#CreateDateColumn()
created_at: Date;
#UpdateDateColumn()
updated_at: Date;
}
#Entity('users')
class User {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
#OneToMany(() => Tasks, task => task.user)
tasks: Tasks[];
#Column({
unique: true,
})
email: string;
#Column()
password: string;
#CreateDateColumn()
created_at: Date;
#UpdateDateColumn()
updated_at: Date;
}
Repositories:
public async findAll(): Promise<Tasks[]> {
return this.ormRepository.find({ relations: ['user'] });
}
public async findByAll(): Promise<User[]> {
return this.ormRepository.find({
relations: ['tasks'],
});
}
when I try to get a get, to get the user's listing, along with the tasks created by that user. the column value is null
and if i do a get on tasks it returns me user as null
[
{
"id": "91d9c552-64e7-4f64-b6e8-b8cfc9c6323a",
"name": "teste do teste",
"status": "NEW",
"description": "testeteste do testeteste do testeteste do teste",
"created_at": "2021-04-16T11:23:01.144Z",
"updated_at": "2021-04-16T11:23:01.144Z",
"user": null
}
]
[ {
"id": "ba2673a6-1d76-4294-98d1-3dc4556733d7",
"name": "Wesley9",
"email": "wesley19#email.com",
"password": "$2a$08$xTprPchGJj3vy3vRfa2P2OWHn5V.hqMh8gQn7323J1wi7WjeWXzbG",
"created_at": "2021-04-16T11:22:28.617Z",
"updated_at": "2021-04-16T11:22:28.617Z",
"tasks": []
}
]
How can I save data in manytomany relationship??
(user, book (MTM))
here is a many-to-many relationship between the user and the book.
My service is not correct.
Also, my code doesn't work.
The data is stored in the book table.
I need your help, everything
Thank you in advance.
My Stack => NestJs, TypeORM, MySQL
There are my entities.
enter image description here
user.entity
#Entity('User')
export class User {
#PrimaryGeneratedColumn()
id!: number;
#Column()
real_name!: string;
#Column()
nick_name!: string;
#Column()
#IsEmail()
email!: string;
#Column()
password!: string;
#Column()
phone_number!: string;
#Column()
image_url: string;
#BeforeInsert()
async hashPassword() {
this.password = await argon2.hash(this.password, {type: argon2.argon2id, hashLength: 40});
}
}
book.entity
#Entity('Book')
export class Book {
#PrimaryGeneratedColumn()
id!: number;
#Column()
title: string;
#Column()
image_url: string;
#Column()
contents: string;
#Column({ type: 'datetime'})
datetime: string;
#ManyToMany(() => User)
#JoinTable()
users: User[];
}
book.controller.ts
#UseGuards(JwtAuthGuard)
#Post('bpc')
savebpc(#Req() req: any, #Query('title') bookTitle: string){
return this.BookService.addBpc(req, bookTitle);
}
book.service.ts
async addBpc(req: any, bookTitle: string): Promise<any>{
const userId = req.user.id;
const bookId = await getRepository('Book')
.createQueryBuilder('book')
.where({title:bookTitle})
.getRawOne()
if (!bookId){
throw new NotFoundException('Not_found_book');
}
const user = await getRepository('User')
.createQueryBuilder('user')
.where({id: userId})
.getRawOne()
//bookId.user.push(user);
//await this.bookRepository.save(bookId);
let userdata = new User();
userdata.id = user.user_id;
userdata.real_name = user.user_real_name;
userdata.nick_name = user.user_nick_name;
userdata.email = user.user_email;
userdata.password = user.user_password;
userdata.image_url = user.user_image_url;
console.log(userdata);
let bookBpc = new Book();
bookBpc.title = bookId.book_title;
bookBpc.image_url = bookId.book_image_url;
bookBpc.contents = bookId.book_contents;
bookBpc.datetime = bookId.book_datetime;
bookBpc.users = [user];
console.log(bookBpc);
await this.bookRepository.create([bookBpc]);
return 'suceess';
}
you need to add the manytomany relation in both user and book, here is an exemple using express and typeorm but its the samething with nestjs
user entity :
#Entity()
export class User {
#PrimaryGeneratedColumn()
id: number;
#Column({ type: 'varchar', nullable: false, unique: true })
username: string;
// we need to add a default password and get it form the .env file
#Column({ type: 'varchar', nullable: true, default: '' })
password: string;
#Column({ type: 'varchar', nullable: true })
firstname: string;
#Column({ type: 'varchar', nullable: true })
lastname: string;
#Column({ type: 'varchar', nullable: false })
email: string;
#Column({ type: 'boolean', nullable: true, default: false })
connected: boolean;
#CreateDateColumn({ name: 'created_at' })
createdAt: Date;
#UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
// new properties
#Column({ name: 'login_attempts', type: 'int', default: 0, nullable: true })
loginAttempts: number;
#Column({ name: 'lock_until', type: 'bigint', default: 0, nullable: true })
lockUntil: number;
//Many-to-many relation with role
#ManyToMany((type) => Role, {
cascade: true,
})
#JoinTable({
name: "users_roles",
joinColumn: { name: "userId", referencedColumnName: "id" },
inverseJoinColumn: { name: "roleId" }
})
roles: Role[];
}
role entity :
#Entity()
export class Role {
#PrimaryGeneratedColumn()
id: number;
#Column({ type: 'varchar', nullable: false, unique: true })
profile: string;
#Column({ type: 'varchar', nullable: false })
description: string;
//Many-to-many relation with user
#ManyToMany((type) => User, (user) => user.roles)
users: User[];
#CreateDateColumn({ name: 'created_at' })
createdAt: Date;
#UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
}
and this is how to save data in user_role :
let entity = await this.userRepository.create(data); //here you create new dataobject that contain user columns
let entity2 = { ...entity, roles: data.selectedRoles } // you have to add the association roles here
const user = await this.userRepository.save(entity2);
I'm going crazy.
I have this JSON:
{
'name': 'Help Me',
'filters': {
'filter1': {
'filter_id': 'wow',
'filter_query': 'maw',
},
'filter2': {
'filter_id': 'wow',
'filter_query': 'maw',
}
}
}
And i'm trying to get this in this way:
export interface MyObject {
name: string;
filters: Filters;
}
export interface Filters {
[key: string]: QueryFilter;
}
export interface QueryFilter {
filter_id: string;
filter_query: string;
friendly_filter_query: string;
}
Or in this way:
export interface MyObject {
name: string;
filters: Map<string, QueryFilter[]>;}
But in first case i got this error message:
Property 'filters' is missing in type '{ 'name': string; ...'.
And in the second case i got this:
Property 'clear' is missing in type '{ 'filter1': { 'filter_id': string; 'filter_query': string; }...'.
I really can't figure out.