我有以下服务:
private vulnerabilityDescriptionSource: BehaviorSubject<
VulnerabilityDescription
> = new BehaviorSubject(new VulnerabilityDescription());
public vulnerabilityDescription: Observable<
VulnerabilityDescription
> = this.vulnerabilityDescriptionSource.asObservable();
public getVulnerabilityDescriptions(vulerabilityId: string) {
return this.http
.get<VulnerabilityDescriptionResponse>(
Endpoints.getvulnerabilityDescriptions(vulerabilityId)
)
.subscribe(
(vulnerabilityDescriptionResponse: VulnerabilityDescriptionResponse) =>
vulnerabilityDescriptionResponse.data.vulnerabilityDescription
);
}
我这样拨打服务电话:
public vulnerabilityDescription: Observable<VulnerabilityDescription> = this
.vulnerabilityService.vulnerabilityDescription;
ngOnInit() {
this.vulnerabilityService.getVulnerabilityDescriptions(this.vulnerability.type);
}
当我打开页面时,可以在“网络”标签中看到正确的数据传输。 我的问题是,当我想通过html中的插值访问数据时,什么也没有出现,就没有错误或任何提示。
这是我尝试显示数据的方式:
<div *ngIf="vulnerabilityDescription | async as vulnerabilityDescription">
{{vulnerabilityDescription.shortdescription}}
</div>
<div class="tab-pane fade show active" [attr.id]="'v'+vulnerability.id+'description'" role="tabpanel" aria-labelledby="v-pills-home-tab">
{{(vulnerabilityDescription | async )?.shortdescription}}
我想念什么?
谢谢您的帮助。
答案 0 :(得分:0)
您必须将.subscribe放在您的component.ts上,因为您只能访问
.subscribe((result:VulnerabilityDescriptionResponse) =>{
//what i want to do whit the result from the call
this.vulnerabilityDescription = result;
}
因此,要解决您的问题,您的服务必须成为
private vulnerabilityDescriptionSource: BehaviorSubject<
VulnerabilityDescription
> = new BehaviorSubject(new VulnerabilityDescription());
public vulnerabilityDescription: Observable<
VulnerabilityDescription
> = this.vulnerabilityDescriptionSource.asObservable();
public getVulnerabilityDescriptions(vulerabilityId: string) {
return this.http
.get<VulnerabilityDescriptionResponse>(
Endpoints.getvulnerabilityDescriptions(vulerabilityId)
);
}
在您的component.ts中
import { yourServiceClassName} from "where is the service";
export class Component implements OnInit {
//inject your service
constructor(private yourService:yourServiceClassName) { }
ngOnInit() {
this.yourService.subscribe(result =>{
this.vulnerabilityDescription = result;
}
}
在您的模板component.html
中从其中删除| async
它应该可以工作