2017-12-05 12 views
0

ムービーデータベースで作業していますが、私はMovieDb APIを使用しています。私は現在、ユーザーの入力なしで20ランダムに生成されたムービーがあるので、私はAPIが動作していることを知っている。角4 - コンポーネント間の文字列の受け渡し

私はこの方法を有効にするには、映画名やボタンを取り込むための入力と私のHTMLがあります。

<button id="searchBarButton" (click)="sendRequest(MovieTitle)">Search</button> 
<input id="MovieTitle" class= "searchBar" type="text" #MovieTitle> 

ザ・サーチcomponent.Iのための私.TSでは、私へのサブスクリプションを設定していますあなたは、私がHTML上のユーザーから取り込んだ映画のタイトルを送るとして、以下のサービスに送信しようとしています見ることができるように

sendRequest(value) 
{ 
// Need to route the shit outta this 
this._iMDBService.searchMDBMovie(this.MovieTitle).subscribe(shows => { 
    this.searchedShows=shows.results; 
    this.router.navigateByUrl("/details"); 
}, 
    error=>this.errorMessage=<any>error); 
} 

を:私はAPIを使用して、それを検索することができますサービス.tsファイル

@Injectable() 
    export class iMDBService { 
    private _iMDBURL: string = 'https://api.themoviedb.org/3/'; 

    constructor(private _http: HttpClient) { } 

    searchMDBMovie(MovieTitle) : Observable<any>{ 
     return this._http.get<any>(this._iMDBURL + 'search/movie?api_key=MyWorkingApiKey&language=en-US&query=' + MovieTitle + '&page=1&include_adult=false') 
     .do(data => console.log('All: ' + JSON.stringify(data))) 
     .catch(this.handleError); 
    } 

    private handleError(err: HttpErrorResponse) { 
     console.log(err.message); 
     return Observable.throw(err.message); 
    } 
} 

私の質問:apiは動作していますが、apiリクエストとHTMLの間に映画タイトルが必要です.tsはservice.tsに送信しません.titlenameをservice.tsファイルにどのように持ってきますか?

+0

RRForUI

答えて

1

#MovieTitle 

変数テンプレートは、入力要素自体ではなく、その値を指します。あなたがする必要がある値を取得するには、次の

<button id= "searchBarButton" (click)= "sendRequest(MovieTitle.value)">Search</button> 

をしても、むしろ冗長再びtempalte変数にアクセスしようとしているよりも、あなたのコンポーネントメソッドでその値を使用します。

コンソールのロギングとデバッグでは、これらの問題が大幅に改善されます。

0

さて、この小さな修正は、それが仕事になるだろうIゲスト:

<button 
    id= "searchBarButton" 
    (click)="sendRequest(MovieTitle.value)"> 
    Search 
</button> 
<input 
    id="MovieTitle" 
    class="searchBar" 
    type="text" 
    #MovieTitle /> 


sendRequest(value) { 
    this._iMDBService.searchMDBMovie(value).subscribe(shows => { 
    ... 

ユーザーとの対話のためにそれを改善するための提案:

<button 
    id= "searchBarButton" 
    (click)="sendRequest(MovieTitle.value)"> 
    Search 
</button> 
<input 
    id="MovieTitle" 
    class="searchBar" 
    type="text" 
    #MovieTitle 
    (keyup.enter)="sendRequest(MovieTitle.value)" /> 

(keyup.enter)は、ときに、ユーザーsendRequestメソッドを呼び出します入力がフォーカスされているときにEnterキーに当たる。

関連する問題