Issue
I am trying to create a generic table component using this tutorial. I implemented the first part, but it doesn't seem to work.
Here is my decorator:
export const tableSymbol = Symbol("table");
export function Column(options: Partial<ColumnModel> = {}) {
return function(target: any, propertyKey: string) {
if (!target[tableSymbol]) {
target[tableSymbol] = new TableModel();
}
options.key = options.key || propertyKey;
const columnOptions = new ColumnModel(options);
target[tableSymbol].addColumn(columnOptions);
};
}
and the model:
export class User {
@autoserializeAs(Number)
@Column()
id: number;
@autoserializeAs(String)
@Column()
name: string;
@autoserializeAs(String)
@Column()
username: string;
}
and my component:
export class TableComponent implements OnInit {
private _data: User[];
private _tableModel: TableModel;
columns: ColumnModel[];
displayedColumns: string[];
@Input() set data(values: any[]) { // Because AsyncPipe is used
if (values) {
this._data = cloneDeep(values);
if (values.length) {
this._tableModel = this._data[0][tableSymbol];
this.buildColumns();
}
}
}
get data(): any[] {
return this._data;
}
private buildColumns() {
this.columns = this._tableModel.columns;
this.displayedColumns = this.columns.map(col => col.key);
}
constructor() { }
ngOnInit(): void { }
}
the TableComponent is used here, in UserListComponent:
export class UserListComponent implements OnInit {
constructor(private repository: UserRepository) {}
ngOnInit(): void {}
getUsers(): User[] {
let repoUsers = this.repository.getUsers();
return repoUsers;
}
}
<common-table [data]="getUsers()"></common-table>
The repository is like this:
export class UserRepository {
private users: User[] = [];
constructor(private dataSource: RestDataSource) {
this.dataSource.getUsers().subscribe(data => {
this.users = <User[]> data;
});
}
getUsers(): User[] {
return this.users;
}
}
And RestDataSource is like this:
const base_url = 'https://jsonplaceholder.typicode.com/';
export class RestDataSource {
constructor(private http: HttpClient) { }
getUsers(): Observable<User[]> {
return this.http.get<User[]>(`${base_url}users`);
}
}
When I run this, it says the tableSymbol is undefined, which means it didn't execute the Column function. I've also uploaded my source code here. Can anyone tell me what did I do wrong?
I'm using angular V9.1 and typescript V3.8
Solution
Turned out that it was a problem in my dataSource. I had a function that was supposed to return an Observable of Users, but it wasn't casting the object to User. I changed it to this, and it worked like a charm.
export class RestDataSource {
constructor(private http: HttpClient) { }
getUsers(): Observable<User[]> {
return this.http.get(`${base_url}users`)
.pipe(
map((res: JsonArray) => DeserializeArray(res, User))
);
}
}
Answered By - Maddie
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.