Angular 4 中的类变量声明和访问

spa*_*rkr 0 model http typescript angular

我有以下模型:

export class User {
  email: string;
  token: string;
  username: string;
  bio: string;
  image: string;
  constructor() {}
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在另一个 Typescript 文件中实例化它时,它抱怨它不能,如下面的屏幕截图所示:

IDE截图

关于为什么我不能实例化它并在这个模型中设置所有属性的任何想法?

编辑:根据以下帖子的建议,我仍然无法修复它!这是屏幕截图!

在此处输入图片说明

Bee*_*ice 5

该关键字let不应在该上下文中使用。使用以下方法之一:

private payload = new User(); // if you don't want this accessible outside the class
public payload = new User(); // if class outsiders should access it directly
Run Code Online (Sandbox Code Playgroud)

你问:

实例化后如何在模型中设置属性?

为组件执行此操作的正确位置是ngOnInit生命周期钩子。这是 Angular 在您的组件初始化后(但在视图准备好之前)执行的代码

export class MyComponent implements OnInit {

  private someProperty:int;

  ngOnInit(){
    this.someProperty = 7;
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您有很多工作要做,只需从ngOnInit. 在上面的代码中,您有一项服务。因为这不是一个组件,所以它不能使用这个生命周期钩子。如果您在编写代码时已经知道该属性的值(从您的第二个屏幕截图看来您确实知道),您可以直接设置它:

private payload:User = {
  email: '...',
  token: '...'
}
Run Code Online (Sandbox Code Playgroud)

但是很可能你不知道所有这些东西,它会被设置为一个函数的结果。那么正确的方法是拥有一个初始化函数,您可以从将使用该服务的组件调用该函数。

@Injectable()
export class UserService {
  private isInitialized:boolean = false;
  private payload:User;

  public init(){
    // init() should only run once
    if(this.isInitialized) return;

    this.payload = new User();
    this.payload.email = '...';
    this.payload.token = this.someFunction();

    // to prevent init() from running again
    this.isInitialized = true;
  }

  private someFunction(){return 'token';}
}
Run Code Online (Sandbox Code Playgroud)

然后在任何组件中,您需要做的就是this.userService.init()在使用它之前调用它。

注意 1:对于具有单个全局实例的服务,它必须列在providersmain的数组中,AppModule并且不能在其他任何地方提供。

注意 2:如果初始化涉及异步代码,例如从远程位置获取数据,您将需要小心返回承诺或 Observable,并让您的代码等到它解析尝试使用服务。