2017-03-26 8 views
1

私は最初のAngularアプリを構築しています。私が取り組んでいるコンポーネントは画像検索ボックスです。ユーザーが検索クエリを入力し、リクエストがAPIに送信され、APIがJSONデータで応答します。 * ngForループが機能しないのはなぜですか? iterableは、サーバーが応答を送信するときに更新されます。サーバからのリクエストが完了したときにテンプレートのレンダリング結果が返されます

画像search.component.ts

import { Component, OnInit } from '@angular/core'; 
import { ImageSearchService } from './image-search.service'; 
import { Image } from '../shared/image'; 

@Component({ 
    selector: 'vb-image-search', 
    templateUrl: './image-search.component.html', 
    styleUrls: ['./image-search.component.css'], 
    providers: [ImageSearchService] 
}) 
export class ImageSearchComponent implements OnInit { 
    images: Image[] = []; 
    constructor(private ImageSearchService: ImageSearchService) { } 

    ngOnInit() { 
    } 

    getImages(query: string) { 
    this.ImageSearchService.getImages(query) 
          .subscribe(function(images) { 
           this.images = images; 
          }); 
    } 

    onClick(query:string) { 
    this.getImages(query); 
    } 

} 

画像search.service.ts

import { Injectable } from '@angular/core'; 
import { Observable } from 'rxjs/Observable'; 
import { Http, Response } from '@angular/http'; 

import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/map'; 

import { Image } from '../shared/image'; 


@Injectable() 
export class ImageSearchService { 

    constructor(private http: Http) {} 

    getImages(query: string): Observable<any[]> { 
    return this.http.get(`http://localhost:3000/api/search/${query}`) 
        .map(this.extractData) 
    } 

    private extractData(res: Response) { 
    let body = res.json(); 
    return body.data.map(e => new Image(e.farmID, e.serverID, e.imageID, e.secret)) || {}; 
    } 
} 

image.ts

export class Image { 
    constructor(public farmID: string, public serverID: string, public imageID: string, public secret: string) { 
    this.farmID = farmID; 
    this.serverID = serverID; 
    this.imageID = imageID; 
    this.secret = secret; 
    } 
} 

画像search.component.html

<div class="col-lg-6 col-md-6"> 
    <div class="input-group"> 
    <input type="text" [(ngModel)]="query" class="form-control" placeholder="Search for images..." /> 
    <span class="input-group-btn"> 
     <button (click)="onClick(query)" class="btn btn-default" type="button">Go!</button> 
    </span> 
    </div> 
    <h2>Images</h2> 
    <div *ngFor="let image of images"> 
    {{image.imageID}} 
    </div> 
</div> 
+0

あなたは 'onClick'と呼ばれる' getImages'を定義しました。あなたはそれが動作していることを確認しましたか? 「画像」はいっぱいですか?コンソールエラーはありますか? – aug

答えて

2

理由は非常に簡単です。 typescriptでは、function(){}を使用すると、現在のスコープを保持するために関数のコールバックが現在のスコープを失うので、代わりに=> {}を使用する必要があります。ですから、下記のように現在のgetImagesメソッドを変更してください。

getImages(query: string) { 
     this.ImageSearchService.getImages(query) 
         .subscribe(images => { 
          this.images = images; 
         }); 
} 
+0

これで動作しました。ご協力いただきありがとうございます! – galaxy233

+0

素晴らしい。@ galaxy233心はそれを投票する! –

関連する問題