我在使用Angular 4时遇到问题。当我运行ng serve
时,TypeScript无法编译并出现错误。
my-data.service.ts中的错误(9,30)找不到名称'类别'
my-data.service.ts中的错误(13,17)找不到名称“类别”
我-data.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';
@Injectable()
export class MyDataService {
database:string = 'http://localhost/exploremo2/material/database/';
database2:string = 'http://192.168.254.105/exploremo2/material/database/';
constructor(private http: Http) {}
getCategories(): Observable<Category[]>{
return this.http.get(this.database+'getdata/getallcategory.php')
.map(res => {
return res.json().results.map(item => {
return new Category(item);
});
});
}
}
add.component.ts
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { fadeInAnimation } from '../_animations/fadein';
import { slideInOutAnimation } from '../_animations/slide';
import { MyDataService} from '../my-data.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-add',
templateUrl: './add.component.html',
styleUrls: ['./add.component.css','../app.component.css'],
providers: [Title],
animations: [slideInOutAnimation],
})
export class AddComponent implements OnInit {
private Categories:Observable<any>;
constructor( private title: Title, private MyDataService:MyDataService) {
this.title.setTitle('Add');
}
ngOnInit() {
this.Categories = this.MyDataService.getCategories();
}
}
答案 0 :(得分:2)
您永远不会在脚本文件中导入类别,但在Observable
中将其用作返回类型。
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';
// ADD IMPORT STATEMENT
import { Category } from './some-file`
@Injectable()
export class MyDataService { /* no change from OP */ }
或者,您可以执行以下操作之一
Category
更改为any
,如果您不在代码本身对这些实例执行任何操作,但仅使用模板中的实例,因为模板不会从类型中受益,这可能没问题安。在服务文件中导出类别
export interface Category {
// members here
}