我正在使用Angular 9,并且正在尝试渲染Mat-Table。
如果我使用硬编码数据,则可以很好地工作,但是,如果我使用服务中的数据,则值不会显示在表中。
例如,以下代码会在第一秒内将硬编码的ELEMENT_DATA
加载到表中,直到返回服务数据为止。
然后,当服务数据返回时,它仅显示表中的空行列表。
这意味着加载从服务返回的数据时出现问题。
let resp: Observable<Approvals[]> = this.service.getApprovalList();
resp.subscribe((approvals: Approvals[]) => {
console.log(approvals);
this.dataSource.data = approvals;
});
从服务返回的JSON数据:
[{"organisation":"xyz"},{"organisation":"xyz"},{"organisation":"xyz"},{"organisation":"xyz"},{"organisation":"xyz"},{"organisation":"xyz"},{"organisation":"xyz"},{"organisation":"xyz"}]
(如果我将此JSON复制到硬编码数据中,则可以正确显示)
问题
有人知道我在做什么错,以便实时数据不显示吗?
approval-list.component.html
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!-- organisation Column -->
<ng-container matColumnDef="organisation">
<th mat-header-cell *matHeaderCellDef> Organisation </th>
<td mat-cell *matCellDef="let element"> {{element.organisation}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
approval-list.component.ts
export interface PeriodicElement {
organisation: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
{organisation: '1'},
{organisation: '2'},
{organisation: '3'}
];
@Component({
selector: 'app-approval-list',
templateUrl: './approval-list.component.html',
styleUrls: ['./approval-list.component.css']
})
export class ApprovalListComponent implements OnInit {
//ELEMENT_DATA: Approvals[];
displayedColumns: string[] = ['organisation'];
dataSource = new MatTableDataSource<Approvals>(ELEMENT_DATA);
constructor(private service: ApprovalService) { }
ngOnInit(): void {
this.loadApprovalData();
}
public loadApprovalData(): void {
let resp: Observable<Approvals[]> = this.service.getApprovalList();
resp.subscribe((approvals: Approvals[]) => {
console.log(approvals);
this.dataSource.data = approvals;
});
}
}
approval.service.ts
@Injectable({
providedIn: 'root'
})
export class ApprovalService {
constructor(private http: HttpClient) { }
public getApprovalList() : Observable<any> {
let tokenStr: string = 'Bearer '+sessionStorage.getItem('jwt');
const headers = new HttpHeaders().set("Authorization", tokenStr);
return this.http.get("http://localhost:8080/approvals", {headers, responseType: 'text' as 'json'});
}
}
approvals.ts
export interface Approvals {
organisation: string;
}
答案 0 :(得分:0)
如果尝试怎么办?
resp.subscribe((approvals: Approvals[]) => {
console.log(approvals);
this.dataSource = new MatTableDataSource(approvals);
});
答案 1 :(得分:0)
问题是因为在服务中,我有:responseType: 'text' as 'json'
。当我删除它时,它会起作用。
public getApprovalList() : Observable<any> {
let tokenStr: string = 'Bearer '+sessionStorage.getItem('jwt');
const headers = new HttpHeaders().set("Authorization", tokenStr);
return this.http.get("http://localhost:8080/approvals", {headers});
}