【发布时间】:2017-09-27 03:42:21
【问题描述】:
我正在尝试使用异步管道,但没有显示数据。我正在记录来自服务器的数据,它在控制台中显示良好。但由于某种原因,我无法让异步工作。
shift.service.ts
import { Injectable } from '@angular/core';
import { Shift } from '../shift/shift';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ShiftService {
constructor(private shift:Shift, private httpClient:HttpClient
) { this.checkShiftStatus();}
checkShiftStatus():Promise<Shift>{
this.httpClient.get<Shift>('http://localhost:8080/shift/isopen')
.subscribe((data) => {
this.shift = data;
console.log(this.shift);
},
error => {
console.error('Something went wrong while trying to check the shift!');
});
return Promise.resolve(this.shift);
}
}
shift.component.ts
import { Component, OnInit } from '@angular/core';
import { Shift } from './shift';
import { ShiftService } from '../services/shift.service';
@Component({
selector: 'app-shift',
templateUrl: './shift.component.html',
styleUrls: ['./shift.component.css']
})
export class ShiftComponent implements OnInit {
isShiftOpen:Promise<boolean>;
shiftLive:Promise<Shift>;
constructor(private shiftService: ShiftService, public shift:Shift) { }
ngOnInit() {
this.isShiftOpen = this.getShift().then(shift => this.shift.active = shift.active);
this.shiftLive = this.shiftService.checkShiftStatus();
}
getShift(){
return this.shiftService.checkShiftStatus().then(shift => this.shift = shift);
}
}
shift.component.html
<md-grid-list *ngIf="isShiftOpen | async" cols="2" rowHeight="100px">
<md-grid-tile>
<button md-raised-button [disabled]='isShiftOpen' color="primary">Open Shift</button>
<button md-raised-button [disabled]='!isShiftOpen' color="warn">Close Shift</button>
</md-grid-tile>
</md-grid-list>
<md-card class="card">
<md-card-title>
Shift Stats:
</md-card-title>
<md-card-content>
</md-card-content>
</md-card>
<!-- <div *ngIf="(shiftLive | async)?.notnull; else loading"> -->
<div *ngIf="shiftLive | async">
<p> Shift status: {{ shiftLive.active }} </p>
<p> Tickets Sold: {{ shiftLive.totalNumberOfTicketsSold }} </p>
</div>
<ng-template #loading>Loading Data...</ng-template>
即使服务提供的值为 true,按钮也不会显示。我确实让 div 显示,但 shiftLive.active 或 shiftLive.totalNumberOfTicketsSold 没有价值。
【问题讨论】:
标签: angular