如何访问接口打字稿中的属性
您好,我想从可观察的接口内访问属性。
我在这个界面中有两个属性。 loan-grade.ts
export interface LoanGrade{
grade:string
subgrade: string
}
我使用 subscribe 来访问 Observable
grades: LoanGrade[];
ngOnInit():void{
this.termGradeServie.termGradeData$.subscribe(grades=>{
this.grades = grades;
})
}
然后在我的 html 中我想打印出我得到的可观察到的所有成绩。但我不能做 item.grade。我该怎么做? edit.component.html
<ng-container *ngFor="let item of grades">
<tr>
<td><span>{{item.grade}}</span></td>
</tr>
</ng-container>
我认为问题是,当我订阅 termGradeData$ 时,它返回 observable(LoanGrade[]) 所以我无法帮助自己将 this.grades
设置为 LoanGrade[]。但如果我将其设置为 LoanGrade[],我将无法访问坡度或路基的属性。
Hi I want to access the property inside the interface from observable.
I have two properties inside this interface.
loan-grade.ts
export interface LoanGrade{
grade:string
subgrade: string
}
I use subscribe to access Observable<LoanGrade[]>.
edit.component.ts
grades: LoanGrade[];
ngOnInit():void{
this.termGradeServie.termGradeData$.subscribe(grades=>{
this.grades = grades;
})
}
Then in my html I want to print out all the grades that exist from observable I got. But I cannot do item.grade. How can I do this?
edit.component.html
<ng-container *ngFor="let item of grades">
<tr>
<td><span>{{item.grade}}</span></td>
</tr>
</ng-container>
I think the problem is that when I subscribe termGradeData$ it returns observable(LoanGrade[]) so I can't help myself to set this.grades
as LoanGrade[]. But if I set it to LoanGrade[], I cannot access the property of grade or subgrade.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的服务中,请确保使用
LoanGrade[]
类型编写可观察对象:并且在代码中的某个位置它会获取一个值(例如,通过将其连接到
http.get方法)。
如果您需要自己为其设置一个值,您可以使用“BehaviorSubject”,如下所示:
然后在代码中的某个位置,确保通过BehaviorSubject发出一个值:
然后在您的组件中,您可以执行下面的A或B :
A
并在您的html中:
或
B(读取可观察值的首选方式):
在组件内部:
并在 html 中使用
async
管道:In your service, make sure to write the observable with
LoanGrade[]
type:and that somewhere in the code it gets a value (for example, by connecting it to an
http.get
method).If you need to set a value for it by yourself, you can use 'BehaviorSubject` as follows:
then somewhere in the code, make sure a value is emitted through the BehaviorSubject:
Then in your component, you can do either A or B below:
A
and in your html:
or
B (preferred way of reading observables):
inside the component:
and use the
async
pipe in your html: