[英]Identifier refers to a private member in angular
I am trying to define a model
in angular and use it html. 我试图在角度定义
model
并使用html。 Here is my code: 这是我的代码:
'user.model.ts' 'user.model.ts'
export class User{
private name: string;
constructor($name: string){
this.name = $name;
}
public get $name(): string {
return this.name;
}
public set $subject(value: string) {
this.name = value;
}
}
component.ts component.ts
myUsers: Array<User>;
ngOnInit(){
//api call
this.myUsers= resultFromAPi;
}
component.html component.html
<div *ngFor="let user of myUsers">
{{user.name}}
</div>
Now, although in the UI, I can see the name and it works perfectly. 现在,尽管在用户界面中,我仍然可以看到该名称,并且可以正常使用。 But at the same time in my code editor(VS code), I am seeing an error:
但是同时在我的代码编辑器(VS代码)中,我看到一个错误:
[Angular] Identifier 'name' refers to a private member of 'User'
I know I can fix the error by making the fields public, but I think that would be bad design. 我知道我可以通过将字段公开来解决错误,但是我认为那是不好的设计。
Update 更新
{{user.$name}}
does not even show the name on UI {{user.$name}}
甚至不在用户界面上显示名称
So why is your template code include {{user.name}}
when you defined a public getter named $name
? 那么,在定义名为
$name
的公共获取方法时,为什么模板代码包含{{user.name}}
?
{{user.name}}
should be 应该
{{user.$name}}
Or change your User
class member names. 或更改您的
User
类成员名称。 The other code that does not make sense to me is calling your setter $subject
. 其他对我来说没有意义的代码是调用setter
$subject
。 This would confuse me if I inherited your code or had to do something in the template after you created it. 如果在您创建代码后我继承了您的代码或必须在模板中执行某些操作,这会使我感到困惑。 Use intuitive and consistent names for your fields and access properties.
为您的字段和访问属性使用直观一致的名称。
Personally I would have just had a public field name
or a private field $name
with public getter name
. 就我个人而言,我将只有一个公共字段
name
或一个带有公共getter name
的私有字段$name
name
。
Seems you have issues in code you have not shown, based purely on trend for this type of question I recommend you just create an interface based on the incoming json
and return that from your service. 似乎完全基于这种问题的趋势,代码中仍存在未显示的问题,我建议您仅基于传入的
json
创建一个接口,然后从服务中返回该接口。
import { HttpClient } from '@angular/common/http';
export interface IUser {
name: string;
}
export class UserService {
constructor(private httpService: HttpClient) {}
getUsers(): Observable<IUser[]> {
return this.httpService.get<IUser[]>('your user end point here');
}
}
When we are using AOT (ahead of time) compiler, all the template members such as properties and method must be define in public. 当我们使用AOT(提前)编译器时,所有模板成员(例如属性和方法)必须在公共位置定义。 you can't access private properties in your templates if you want to use ahead-of-time compilation.
如果要使用提前编译,则无法访问模板中的私有属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.