我是IONIC/Angular和Javascript的新手,但在其他语言方面有一些背景。我面临的问题是,我从外部API获得JSON数据(我用Strapi创建了API),我正在获得响应,但无法在视图
上显示它们这是我的代码在这里输入图像描述vowels.service.tsimport { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
// Typescript custom enum for search types (optional)
export enum SearchType {
all = '',
vowels = 'vowel',
easy = 'easy',
hard = 'hard',
naglos = 'naglos',
wyglos = 'wyglos',
srodglos = 'srodglos'
}
// Typescript custom enum for search types (optional)
export enum Categories {
all = '',
naglos = 'naglos',
wyglos = 'wyglos',
srodglos = 'srodglos'
}
@Injectable({
providedIn: 'root'
})
export class VowelService {
url = 'http://localhost:1337/vowels';
/**
* Constructor of the Service with Dependency Injection
* @param http The standard Angular HttpClient to make requests
*/
constructor(private http: HttpClient) { }
/**
* Get data from the local API
* map the result to return only the results that we need
*
* @param {string} title Search Term
* @param {string} vowelType
* @param {Categories} categories easy, hard,
* @returns Observable with the search results
*/
searchData(title: string): Observable<any> {
return this.http.get(`${this.url}?name=${encodeURI(title)}`).pipe(
map(results => results['Search'])
);
}
/* GET only Vowels that has category equal to =
*/
searchVowel(type: Categories): Observable<any> {
return this.http.get(`${this.url}?&categories.name=${type}`).pipe(
map(results => results['Search'])
);
}
/**
* Get the detailed information for an ID using the "i" parameter
*
* @param {string} id imdbID to retrieve information
* @returns Observable with detailed information
*/
getDetails(id) {
return this.http.get(`${this.url}?i=${id}&plot=full`);
}
}
vowels.page.html
<ion-header>
<ion-toolbar color="primary">
<ion-title>Wyszukiwarka samogłosek</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-searchbar [(ngModel)]="searchTerm" (ionChange)="searchChanged($event)"></ion-searchbar>
<ion-item>
<ion-label>Wybierz typ</ion-label>
<ion-select [(ngModel)]="type" (ionChange)="searchChangedVowels($event)">
<ion-select-option value="">Wszystkie</ion-select-option>
<ion-select-option value="naglos">Nagłos</ion-select-option>
<ion-select-option value="srodglos">Śródgłos</ion-select-option>
<ion-select-option value="wyglos">Wygłos</ion-select-option>
</ion-select>
</ion-item>
<ion-list>
<ion-item button *ngFor="let item of (results | async)" [routerLink]="['/', 'vowels', item.id]">
<ion-label text-wrap>
<h3>{{ item.id }}</h3>
<h3>{{ item.name }}</h3>
</ion-label>
</ion-item>
</ion-list>
</ion-content>
vowels.page.ts
import { VowelService, Categories } from './../../services/vowels.service';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-vowels',
templateUrl: './vowels.page.html',
styleUrls: ['./vowels.page.scss'],
})
export class VowelsPage implements OnInit {
results: Observable<any>;
searchTerm: string = '';
type: Categories = Categories.all;
/**
* Constructor of our first page
* @param vowelService The movie Service to get data
*/
constructor(private vowelService: VowelService) { }
ngOnInit() { }
searchChanged() {
// Call our service function which returns an Observable
this.results = this.vowelService.searchData(this.searchTerm);
}
searchChangedVowels() {
// Call our service function which returns an Observable
this.results = this.vowelService.searchVowel(this.type);
}
}
当map操作符使用可观察对象时,您不会在页面中显示数据。
你应该在你的服务文件中使用它:
pipe(map(results => {
return results["search"]
}))
这样你的函数将返回一个Observable。
您还应该将您的vowels.page.ts中的方法更改为:
//Results are type of object or any in my example
results: any || yourDataModelType ;
this.vowelService.searchData(this.searchTerm).subscribe(results => {
this.results = results;
})
通过这种方式,你已经生成了一个可观察对象,并在你从服务器获取数据时在你的页面中使用。
请注意,只有当可观察对象确实返回了一个可以使用的数据时,你才会得到结果。
另一个注意事项是,当你订阅了一个可观察对象时,为了防止内存泄漏,你应该在使用完它后取消订阅。在Ionic/Angular中,你可以在ngOnDestroy()循环中完成。例如:
//Define a subscription variable in your page.ts
sub: Subscription
//Assign it inside your function
this sub = this.vowelService.searchData(this.searchTerm).subscribe(results => {
this.results = results;
})
//Define OnDestroy Cycle for the page
export class VowelsPage implements OnInit, OnDestroy
//Add ngOnDestroy cycle and unsubscribe inside.
ngOnDestroy(){
if(this.sub){sub.unsubscribe()}
}
我建议你对RxJs库进行更深入的研究,并检查Observable类型以更好地理解。https://www.learnrxjs.io/