我从json获得了属性,但它显示了拼写错误,如下所示:类型'any []'不能分配给'typeof User' 下面是我的代码app.component.ts:
import { Component, OnInit } from '@angular/core';
import { User, UserService } from './user.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserService]
})
export class AppComponent implements OnInit {
title = 'Users list';
usersdata:User;
constructor(private userService: UserService) { }
ngOnInit(){
this.userService.getUsers().then(users => this.usersdata = users.data);
}
}
import { Injectable } from '@angular/core';
export class User {
id: number;
name: string;
data=[];
}
export class data {
name:string;
category:string;
}
@Injectable()
export class UserService {
constructor() { }
getUsers(): Promise<User> {
return Promise.resolve(
{ id: 1, name: 'Maria','data':[{
name:'ramu',category:'c'
}]}
);
}
}
以下是我的CODE网址Code URL Stackblitz
答案 0 :(得分:2)
像这样添加类型用户..
return Promise.resolve<User>(
{ id: 1, name: 'Maria','data':[{
name:'ramu',category:'c'
}]}
);
同样在组件更改类型的数据any[]
usersdata:any[];
答案 1 :(得分:1)
尝试以下代码段。
import { Component, OnInit } from '@angular/core';
import { User, UserService,data } from './user.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
title = 'Users list';
usersdata: Array<data>;
constructor(private userService: UserService) { }
ngOnInit() {
this.userService.getUsers().then(users => this.usersdata = users.data);
}
}
<强> DEMO 强>
答案 2 :(得分:0)
在班级User
中,您通过指定一个空数组data
将属性any[]
定义为data = []
类型。
但在您的AppComponent
中,您尝试将userData
(类型User
)分配给user.data
(类型any[]
),这会导致TypeScript错误
要修复错误,您需要使用正确的类型。
选项A:将整个User
对象保存到userdata
usersdata: User;
ngOnInit() {
this.userService.getUsers().then(users => this.usersdata = users);
}
选项B :修复userdata
的类型以匹配User.data
的类型。
usersdata: any[];
ngOnInit() {
this.userService.getUsers().then(users => this.usersdata = users.data);
}