初始化类型后无法再打开页面

时间:2019-02-08 19:31:30

标签: javascript angular typescript ionic-framework ionic4

我编写了一个从API接收数据的服务。我遵循了教程,但是当我添加此部分时

  type: SearchType = SearchType.all;

我无法再打开页面(标签)。因此,该错误可能是由该部分引起的,因为这意味着当我无法打开它时出现错误。我使用的教程是:https://www.youtube.com/watch?v=3QPbBJgNF94&t=1747s

friends.TS

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { SearchType, FriendsService } from '../services/friends.service';


@Component({
  selector: 'app-friends',
  templateUrl: './friends.page.html',
  styleUrls: ['./friends.page.scss'],
})
export class FriendsPage implements OnInit {


  results: Observable<any>;
  searchTerm = '';
  type: SearchType = SearchType.all;


  constructor(private friendsService: FriendsService) { 


  }

  ngOnInit() {
  }

  searchChanged() {
    this.results = this.friendsService.searchData(this.searchTerm, this.type);
  }

}

friends.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';



export enum SearchType {
  all = '',
  movie = 'movie',
  series = 'series',
  episode = 'episode'
}
@Injectable({
  providedIn: 'root'
})
export class FriendsService {
  url = 'http://www.omdbapi.com/'
  apiKey = 'a16a078b';

  constructor(private http: HttpClient) { }

  searchData(title: string, type: SearchType): Observable<any> {
    return this.http.get('${this.url}?s=${encodeURI(title)}&type=${type}&apikey=${this.apiKey}')
    .pipe(
      map(results => results['Search'])
    );


  }

  getDetails(id){
    return this.http.get('${this.url}?i=${id}&plot=full&apikey=${this.apiKey}');

  }
}

friends.html

<ion-header>
  <ion-toolbar color="favorite">

  </ion-toolbar>
</ion-header>

<ion-content padding>

          <ion-list>
          <ion-item *ngFor="let item of (results | async)" [routerLink]="['/', 'friends', item.imdbID]">

           {{ item.Title}}

              </ion-item>
        </ion-list>



</ion-content>

1 个答案:

答案 0 :(得分:0)

friends.service.ts 中进行以下更改:

'${this.url}?s=${encodeURI(title)}&type=${type}&apikey=${this.apiKey}'

对此:

let t = '' if type === SearchType.any else '&type=${type}'
'${this.url}?s=${encodeURI(title)}${t}&apikey=${this.apiKey}'

在HTTP中,当它为空时,我不会添加参数

您可能还希望查看条件。因为如果标题中没有传递任何内容,则s =也无关紧要。