【发布时间】:2018-02-07 21:32:39
【问题描述】:
您好,我想知道如何组织我的代码:
我有一个简单的用户界面:
export interface User {
Account: string;
Name: string;
EMail: string;
PictureURL: string;
Department: string;
JobTitle: string;
Initials: string;
Skype: string;
Office: string;
MobileNumber: string;
DirectLine: string;
IsChecked: boolean;
IsIDTitleOnly: boolean;
ID: string;
CreatedAt: string;
CreatedBy: this;
ModifiedAt: string;
ModifiedBy: this;}
我有一个简单的服务来获取我的数据:
getCurrentUser(): Observable<User> {
const serviceUrl: string = environment.apiUrl + 'Users/Current';
return this.http.get(serviceUrl)
.map((res: User) => {
return res;
});}
最后是一个简单的组件:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { User } from '../../interfaces/user';
import { UserService } from '../../services/user.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
user: User;
constructor(
private userService: UserService
) { }
ngOnInit() {
this.getCurrentUser()
}
getCurrentUser() {
this
.userService
.getCurrentUser()
.subscribe(
res => { console.log(res); this.user = res },
err => { console.log(err); }
)
}
}
我没有为我的用户创建一个类或构造函数,我应该总是创建一个足够的类或接口吗?
当我显示“user.Name”时出现错误:“无法读取未定义的属性 'Name'”,因为用户没有时间恢复数据。
我真的很想知道如何正确初始化我的用户,以及是否需要一个类(如果有一天我必须创建一个新用户)。
在此先感谢
【问题讨论】:
标签: angular angular-services angular-http