2017-06-13 40 views
0

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 

和幾秒鐘後,它加載

+1

你似乎對Promise的工作原理有一個根本性的誤解。您顯然正在嘗試在準備好之前訪問'drawing'成員。你的'getUrl'方法是可能的罪魁禍首。 –

+0

一旦A在未來某個任意點完成,Promise只是一個方便的方法。由於您在A完成之前嘗試訪問B的結果,因此會出現錯誤。 –

回答

0

這個我最有可能是由於這樣的事實:promise會只要將數據返回到該組件之前需要服用。那麼你的組件已經加載了。在填充變量之前,嘗試檢查在HTML文件中是否存在值爲*ngIf。然後它會出現,當它準備就緒,你不應該看到錯誤undefined

+0

我以爲html模板直到ngOnInit完成纔會被渲染。 – filemonczyk

+0

'ngOnInit' * does *完成,但由它觸發的http請求直到幾秒鐘後纔開始。你在你的問題中提到了「異步」,但你似乎沒有意識到這一點。 –

+0

查看此文檔的異步部分。你會明白爲什麼會有延遲。 https://angular.io/tutorial/toh-pt4#async-services-and-promises –