Im在加載時使用數據加載角模板由於調用未定義的屬性,幾秒鐘後,服務器的downlaoding數據完成並且模板加載數據後,出現錯誤。很明顯,有異步問題。但我已經實現了OnInit方法來加載所需的數據到模板,在這裏我很困惑,並要求幫助。未定義模板加載角度(儘管承諾)
@Component({
selector: 'drawing',
templateUrl: './drawing.component.html',
styleUrls: ['./drawing.component.css']
})
export class DrawingComponent implements OnInit{
private drawing: Drawing;
constructor(private drawingService: DrawingService){}
getDrawing(): void {
this.drawingService.getDrawing().then((data) => {this.drawing = data});
}
ngOnInit(): void {
this.getDrawing();
}
getUrl(): string {
return 'http://www.localhost:8080/api/image/' + this.drawing.drawingUrl;
}
下圖類:
export class Drawing {
drawingId: number;
drawingUrl: string;
zoom: number;
rotation: number;
}
以下組件的HTML tempalte
<button (click)="zoomIn()">Zoom In</button>
<button (click)="zoomOut()">Zoom Out</button>
<button (click)="rotateView()">Rotate</button>
<pdf-viewer
id="textLayer"
[src]="getUrl()"
[page]="page"
[original-size]="true"
style="display: block;"
[zoom]="getZoom()"
[render-text]="false"
(click)="getCoordinates($event)"
[rotation]="getRotation()"
></pdf-viewer>
和繪圖服務:
@Injectable()
export class DrawingService {
private drawingUrl = 'http://www.localhost:8080/api/drawing/1';
constructor(
private http: Http){}
getDrawing(): Promise<Drawing> {
return this.http.get(this.drawingUrl).toPromise().then((res) => res.json() as Drawing);
}
}
所以先上載即時得到
ERROR TypeError: Cannot read property 'drawingUrl' of undefined
at DrawingComponent.webpackJsonp../src/app/drawing/drawing.component.ts.DrawingComponent.getUrl
和幾秒鐘後,它加載
你似乎對Promise的工作原理有一個根本性的誤解。您顯然正在嘗試在準備好之前訪問'drawing'成員。你的'getUrl'方法是可能的罪魁禍首。 –
一旦A在未來某個任意點完成,Promise只是一個方便的方法。由於您在A完成之前嘗試訪問B的結果,因此會出現錯誤。 –