2017-08-15 4 views
0

前に読んだことは、iFrameがロードされていないか、onErrorまたはonLoad関数を使用してChromeにロードされているかどうかを検証できないため、iFrameとしてSRCとして提供されたURLをテストすることにしました。単純なhttp取得。iFrame検証http取得SRC

iFrameに特定のURLを読み込み、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

だから、最後に私がHttpErrorResponseを使用couldn'tが、私は私のHTTP GETで深く掘ると、それは明らかに誤りでした。

iFrameの変数URLを設定すると動作し、200 OKを返します。一方、httpを取得すると、受け入れるデータの種類をヘッダーに指定する必要があります。この場合、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); 
    } 

2番目のエラーは、あなたがしようとした場合、通常、あなたが .MAP(this.extractData)

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

won't作業を使用することができ、マップ演算子を使用していましたHTML文書からjson値を抽出します。

0

外部APIからの失敗を確認するには、HttpErrorResponseを使用する必要があります。

どのように使用しますか?

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

残念ながら、私は@ angular/common 4.3が必要で、私が使用できる唯一のバージョンであるバージョン4.0.3を使用しているので、HttpErrorResponseを使用できないと思います。 – sie

関連する問題