错字错误:角度5

时间:2018-02-07 13:29:15

标签: angular typescript

我尝试在interface.ts中创建界面。 data是Column中的一个对象数组。以下是我的界面代码:



export class User {
result: boolean;
messages: string;
Column=[];
data=[];
}
export class Column {  
name:string;
category:boolean;
count:number;
}

export class data {
name:string;
category:string;
}




下面是服务中使用的代码。



getData(): Promise<User> {
return Promise.resolve(
{ result: true, messages: 'Maria','Column':[{
name:'ramu',category:'c',count:4, "data":[{"name":"",      "category":""
    }]
}]
}
);
}
&#13;
&#13;
&#13;

但我得到了类型错误。我已附上屏幕截图请检查。以下是错误屏幕截图。 Code URL Stackblitz

enter image description here

4 个答案:

答案 0 :(得分:0)

试试

  getData(): Promise<User> {
return Promise.resolve(
{ result: true, messages: 'Maria',
  'Column':[{   name:'ramu',category:'c',count:4}], 
 "data":[{ "name":"", "category":"" }]
});
}

答案 1 :(得分:0)

尝试以下代码段。

import { Injectable } from '@angular/core';
import { Http, Headers, Response, URLSearchParams, RequestOptions } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { User } from './interface';
import { Column } from './interface';

import 'rxjs/add/operator/map';

@Injectable()
export class DataService {

  userCookie: any;
  loginAlertMessage: string;
  constructor(private http: Http
  ) {
  }



  getData(): Promise<User> {
    return Promise.resolve(
      {
        result: true, messages: 'Maria',
        'Column': [{ name: 'ramu', category: 'c', count: 4 }],
        "data": [{ "name": "", "category": "" }]
      });
  }
}

<强> DEMO

答案 2 :(得分:0)

试试这个 interface.ts

export class User {
  result: boolean;
  messages: string;
  Column=[];
}
export class Column {  
  name:string;
  category:boolean;
  count:number;
  data=[]; // data should be here in Column class
}
export class data {
  name:string;
  category:string;
}

<强>的DataService

getData(): Promise<User> {
    return Promise.resolve(this.data);
}

WORKING DEMO

答案 3 :(得分:0)

这里的其他一些答案都是有效的。

在我看来,你应该只是“键入断言”对象到你需要的类型(假设数据的格式与你需要的格式正确。)...

getData(): Promise<User> {
    return Promise.resolve(
      {
        result: true, messages: 'Maria',
        'Column': [{ name: 'ramu', category: 'c', count: 4 }],
        "data": [{ "name": "", "category": "" }]
      } as User);
  }

即。在对象的末尾添加as User