2017-08-15 78 views
0

正如我以前閱讀過的,我無法驗證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);),但我總是得到一個未定義的錯誤狀態或消息。任何想法爲什麼?

回答

0

所以,最後我couldn't使用HttpErrorResponse,但我挖我的HTTP GET更深,這是一個明顯的錯誤。

當爲iFrame設置變量URL時,它工作,我得到200 OK,另一方面當我做一個http get時,我必須在我的頭文件中指定我想要接受的數據類型。在這種情況下,它是一個HTML文檔,因此設置請求選項「Accept」:「text/html,...」就可以做到這一點。

的iFrame驗證

getAppStatus(): Observable<String[]> { 
    let url = constant.Url; 
    let headers = new Headers({ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' }); 
    let options = new RequestOptions({ headers: headers }); 

    return this.http.get(url, options) 
     .timeout(2000) 
     .catch(this.handleErrorMessage); 
    } 

用第二個錯誤的地圖運營商,通常你可以使用 .MAP(this.extractData)

extractData(res:Response){ 
    let body = res.json(); 
    console.log('Body', body); 
    return body || []; 
} 

它不需額外的工作,如果你嘗試從HTML文檔中提取json值。

0

您應該使用HttpErrorResponse檢查外部API可能的故障。

如何使用它?

import { HttpErrorResponse } from '@angular/common/http'; 


http 
    .get<ItemsResponse>('api url') 
    .subscribe(

    data => {...}, 

    (err: HttpErrorResponse) => { 
     if (err.error instanceof Error) { 

     // A client-side or network error occurred. Handle it accordingly. 
     console.log('An error occurred:', err.error.message); 

     } else { 

     // The backend returned an unsuccessful response code. 
     // The response body may contain clues as to what went wrong, 
     console.log(`Backend returned code ${err.status}, body was: ${err.error}`); 
     } 
    } 
    }); 
+0

謝謝!我會嘗試,雖然我得到一個「無法找到模塊」的錯誤。我想我必須先安裝軟件包。 – sie

+0

不幸的是我覺得我不能使用HttpErrorResponse,因爲我需要@ angular/common 4.3,而且我使用的是版本4.0.3,這是我可以使用的唯一版本。 – sie