如果用户已订阅,我想显示文本“ Subscribed”,如果没有,则显示“ Subscribe”。为此,我从后端调用一个服务,该服务向我提供对象(如果已订阅),如果没有则抛出错误。现在,无论他是否订阅,我如何更改显示的文本。
我正在使用Angular 7。
import { Component, OnInit } from '@angular/core';
import { CategoryService } from '@ikubinfo/core/services/category.service';
import { Router } from '@angular/router';
@Component({
selector: 'ikubinfo-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
categories: Object;
text: string;
constructor(private categoryService: CategoryService, private router: Router) {
this.categories=[];
this.text='';
}
ngOnInit() {
this.categoryService.getAllCategories().subscribe(res=>{
this.categories=res;
console.log(this.categories);
});
}
subscribe(id: number){
this.categoryService.subscribe(id).subscribe(res=>{
});
}
isSubscribed(id:number){
return this.categoryService.isSubscribed(id).subscribe(res=>{
this.text='Subscribed';
},err=>{
this.text='Subscribe';
});
}
}
还有html
<div class="row">
<div class="col col-xl-6 col-lg-12" *ngFor="let category of categories">
<ikubinfo-panel header="Category">
<div panel-content ng-onload="isSubscribed(category.categoryId)">
<h1>{{ category.categoryName }}</h1>
<p>{{ category.categoryDescription }}</p>
<button class="btn btn-success" (click)="subscribe(category.categoryId)">{{ text }}</button>
</div>
</ikubinfo-panel>
</div>
</div>
答案 0 :(得分:0)
在类别模型中有一个附加属性isSubscribed,
k1
在* .ts文件中,
export interface Category {
... // other existing properties
isSubscribed: boolean = false; // initializing to false by default for error case
}
在* .html文件中,基于此属性显示文本。
ngOnInit() {
this.categoryService.getAllCategories().subscribe(res=>{
this.categories=res;
this.categories.forEach((category) => {
this.categoryService.isSubscribed(id).subscribe(res=>{
category.isSubscribed = true;
});
});
});
}
此外,我建议在获取所有类别的初始请求上获取订阅标志。
答案 1 :(得分:0)
您应该像这样更改isSubscribed()方法:
isSubscribed(id:number) {
return this.categoryService.isSubscribed(id)
.pipe(
//this will map your response to 'Subscribed' text
map(res => 'Subscribed'),
//this map error to 'NotSubscribed
catchError(error => 'Not Subscribed')
);
}
现在让我们像这样更改模板:
<div class="row">
<div class="col col-xl-6 col-lg-12" *ngFor="let category of categories">
<ikubinfo-panel header="Category">
<div panel-content>
<h1>{{ category.categoryName }}</h1>
<p>{{ category.categoryDescription }}</p>
<button class="btn btn-success" (click)="subscribe(category.categoryId)">{{ isSubscribed(category.categoryId) | async}}</button>
</div>
</ikubinfo-panel>
</div>
</div>
尽管我已经按照您当前的代码提供了解决方案。代码改进的范围很大。您应该避免在绑定中的模板中使用函数调用(用户操作(即按钮单击除外))。您也可以通过使用async
管道 [https://blog.angularindepth.com/tiny-angular-pipe-to-make-any-function-memoizable-f6c8fa917f2f]