在我的angular 2项目中,我有一些由angular-cli 1.0.0-rc.0生成的组件。 所以项目src文件夹看起来像这样:
列表:
├── app
│ ├── app.component.html
│ ├── app.component.ts
│ ├── routing.module.ts
│ ├── app.module.ts
│ ├── info
│ │ ├── info.component.html
│ │ └── info.component.ts
│ ├── journal
│ │ ├── journal.component.html
│ │ └── journal.component.ts
│ ├── model
│ │ ├── entity.ts
│ │ └── user.ts
│ ├── roles
│ │ ├── roles.component.html
│ │ └── roles.component.ts
│ └── users
│ ├── users.component.html
│ ├── users.component.ts
│ └── users.service.ts
│
├── favicon.ico
├── fonts
│...
├── img
│ ...
└── index.html
src / model / user.ts 文件具有用户类声明。 无论如何,当我启动我的项目时,我有很多错误,比如
TypeError:this.currentUser.getFullName不是函数
在源代码上的Chrome DevTools中,我没有从模型文件夹中找到我的源文件,可以在this screenshot上看到。
为什么 Webpack 会忽略没有角度组件的文件夹?
AppComponent 类声明:
import {Component, OnInit} from "@angular/core";
import {UsersService} from "./users/users.service";
import {User} from "./model/user";
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(private userService: UsersService) {
}
currentUser: User;
ngOnInit(): void {
this.userService.getCurrentUser().subscribe(user => {
this.currentUser = user;
console.log(user);
});
}
getFullName(): string {
return this.currentUser != null ? this.currentUser.getFullName() : "";
}
}
UsersService 类声明:
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import "rxjs/add/operator/map";
import {Observable} from "rxjs";
import {User} from "../model/user";
@Injectable()
export class UsersService {
private url = 'api/users'
constructor(private http: Http) {
}
getCurrentUser(): Observable<User> {
return this.http.get(`${this.url}/cu`)
.map(response => {
return response.json() as User;
});
}
private handleError(error: any): Promise<any> {
return Promise.reject(error.message || error);
}
}
用户类声明:
import {Entity} from "../model/entity";
export class User extends Entity {
constructor(
public id: number,
public name: string,
public surname: string,
public patronimyc: string,
public login: string
) {
super(id);
};
getFullName():string{
return `${this.surname} ${this.name} ${this.patronimyc}`;
}
}
答案 0 :(得分:1)
在您的服务中,您执行此操作:
return response.json() as User;
这基本上告诉TypeScript:相信我,我知道response.json()
返回的对象是类User
的一个实例。但事实并非如此。 response.json()
只是创建一个愚蠢的JavaScript对象,它不是你的类的实例(Angular如何知道你的类),并且除了所有JS对象之外没有任何方法。
因此尝试在这个哑对象上调用getFullName()
失败了,因为正如消息所说,这种方法不存在。