类型'any []'不能分配给角度5中的'typeof User'类型

时间:2018-02-07 10:40:05

标签: angular typescript

我从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);
}
}
以下是我在user.service.ts中的代码:

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

下面是我的拼写错误屏幕截图。请告诉我我在哪里犯了错误?enter image description here

3 个答案:

答案 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);
}