Javascript 错误:(typescript)意外标记。应为构造函数、方法、访问器或属性
我是Angular 2的初学者。我试着在VisualStudio中编写一些教程。我安装了npm、nodejs和angular/cli。当我在typescript上运行visual studio代码的一些示例时,我在尝试使用javascript编写单词“this”时遇到了错误 只有当我使用javascript单词“this”时才会发生错误,除此之外,它没有错误。有什么解决办法吗?多谢各位Javascript 错误:(typescript)意外标记。应为构造函数、方法、访问器或属性,javascript,angular,typescript,Javascript,Angular,Typescript,我是Angular 2的初学者。我试着在VisualStudio中编写一些教程。我安装了npm、nodejs和angular/cli。当我在typescript上运行visual studio代码的一些示例时,我在尝试使用javascript编写单词“this”时遇到了错误 只有当我使用javascript单词“this”时才会发生错误,除此之外,它没有错误。有什么解决办法吗?多谢各位 import { Component, OnInit } from '@angular/core'; @C
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
name:string = 'John Doe';
age:number = 50;
email:string = 'someone@example.com';
address: {
street:string,
city:string,
postalcode:number
}
constructor() {
console.log('constructor . .. ');
}
ngOnInit() {
console.log('ngonit . . . ');
}
public.address = {
street:'adsadsasd',
city: 'asdsad',
postalcode: 123132
}
}
只有当我使用javascript单词“this”时才会发生错误,除此之外,它没有错误。有什么解决办法吗?多谢各位
不要用它。在TypeScript中,鼓励您以以下方式编写成员:
public address: {...} = {...};
其中,public
是可选的
例如,在您的课堂上,您可以:
public address: {
street:string,
city:string,
postalcode:number
} = {
street:'adsadsasd',
city: 'asdsad',
postalcode: 123132
}
您应该在函数中包装
this.address={..}
您可以将其包装到ngOnInit
函数中
我建议您在单独的类中创建一个模型
export class AddressModel{
constructor(public street:string='', public city:string='', public postalcode:number=0);
}
并在组件.ts中初始化它
address:AddressModel= new AddressModel();
这个代码对我有用。我通过将this.address包装到ngOnIt()函数中进行了更改。谢谢大家。请将代码以内联方式发布,而不是以图像的形式发布。发布代码,而不是代码的图片。更多:从你的代码中删除这个.address,它应该总是在你的类的函数下使用,初始化,公共地址:{city:string,postalCode:string}={city:'Vegas',postalCode:'12345'}或者你可以在ngOnInit()中使用它。很抱歉。我很好奇为什么使用'this'会在typescript中出现错误,因为typescript是javascript的超集。它是<代码>类a{this.x=14}
在JavaScript中给出了相同的错误。@Alexandru IonutMihai您没有。您可以,但如果您使用符合TS的语法,则代码可能位于任何方法之外。@lilezek,是的,但如果您要使用this
则必须将其包装。就像在c#或Java中一样。如果您在没有此项的情况下声明它,就像您声明了一个新属性,但是如果您想访问一个现有属性,您应该将它包装在一个函数中。@Alexandru IonutMihai,谢谢。我试着在ngonit函数中进行包装,结果成功了。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
name:string = 'John Doe';
age:number = 50;
email:string = 'someone@example.com';
address: {
street:string,
city:string,
postalcode:number
}
constructor() {
console.log('constructor . .. ');
}
ngOnInit() {
console.log('ngonit . . . ');
this.address = {
street:'Chicago',
city: 'America',
postalcode: 123132
};
}
}