正如我以前閱讀過的,我無法驗證iFrame是否已加載,未加載或仍然使用onError或onLoad函數在Chrome中加載,因此我決定測試使用SRF作爲iFrame提供的URL一個簡單的http獲取。iFrame驗證http獲取SRC
我開始加載帶有特定URL的iFrame,並使用http get同時檢查URL。如果http get返回200 OK,則表示iFrame已正確加載,因此我隱藏了一條錯誤消息(this.iFrameStatus = false;)。如果http返回錯誤,那麼我應該更改iFrame URL並顯示錯誤消息(this.iFrameStatus = true;)。
組件
export class StatusComponent implements OnInit {
public iFrameUrl: any;
public iFrame: any;
public iFrameStatus: boolean = false;
public counter: number = 0;
public errorMessage: any;
//Assign URL to iFrame in constructor
constructor(private _sanitizer: DomSanitizer, public _element: ElementRef, private _verificationService: VerificationService) {
this.iFrameUrl = this._sanitizer.bypassSecurityTrustResourceUrl(constant.Url);
setTimeout(() => {
this.iFrameStatusVerification();
}, 3000);
}
//Verify if iFrame is correctly loaded
ngAfterViewInit() {
this.iFrame = this._element.nativeElement.querySelector('.iFrame');
}
iFrameStatusVerification() {
this._verificationService.getAppStatus().subscribe(
data => {
console.log('success', data);
this.iFrameStatus = false;
this.iFrameUrl = this._sanitizer.bypassSecurityTrustResourceUrl(constant.Url);
},
error => {
error => this.errorMessage = <any>error
console.log('error', error);
console.log('error status', error.status);
console.log('error ok', error.ok);
this.iFrameStatus = true;
//this.iFrame.src = constant.emptyIFrame;
this.iFrameUrl = this._sanitizer.bypassSecurityTrustResourceUrl(constant.emptyIFrame);
}
);
}
ngOnInit() {
}
}
服務
@Injectable()
export class VerificationService {
//External App iFrame Verification
getAppStatus(): Observable<String[]> {
let url = constant.localServer + constant.Url;
console.log(url);
return this.http.get(url, this._requestOptions)
.timeout(5000)
.map(res => { let body = res.json(); return body; })
.catch((err: any): any => {
this.handleError(err, 'Error app not found ');
//return Observable.of(err);
});
}
handleError(err: any, message: string) {
let errMsg = (err.message) ? err.message :
err.status ? `${err.status} - ${err.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.of(err);
}
}
this._requestOptionsare是注入的服務從中我得到了跨源性質的標題選項。
加載了iFrame,我從URL收到200 OK,但是顯示了錯誤消息,並且src被更改了。我嘗試在組件中打印錯誤狀態或消息(console.log('error status',error.status);),但我總是得到一個未定義的錯誤狀態或消息。任何想法爲什麼?
謝謝!我會嘗試,雖然我得到一個「無法找到模塊」的錯誤。我想我必須先安裝軟件包。 – sie
不幸的是我覺得我不能使用HttpErrorResponse,因爲我需要@ angular/common 4.3,而且我使用的是版本4.0.3,這是我可以使用的唯一版本。 – sie