我正在加载带有数据的角度模板,在加载时由于调用未定义的属性而导致错误,几秒钟后服务器的数据下载完成并且模板加载了数据。所以很明显存在异步问题。但是我已经实现了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;
}
在Drawing类下面:
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
并在几秒钟后加载
答案 0 :(得分:0)
我很可能是因为promise
在将数据返回到组件之前需要的时间。那时你的组件已经加载了。在填充变量之前,请尝试使用*ngIf
检查HTML文件中是否存在值。然后它会在准备就绪时出现,你不应该看到undefined