[英]angular 7 observable array filtering error
我是 Angular 的新手。 目前使用 Angular 7 版本。 我正在嘗試使用 Observable 中的 filter() 方法進行過濾操作。 我創建了一個服務來注入 Httpclient 以從 json 文件加載數據。 數據正在從 json 加載。 現在我正在嘗試基於 EventEmitter 過濾數據。
我收到過濾器不是功能錯誤
country-load.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, filter, switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs'
import 'rxjs';
import { ArrayType } from '@angular/compiler/src/output/output_ast';
import { of } from 'rxjs/internal/observable/of';
/* interface ServerData {
shows: Show[];
} */
@Injectable({
providedIn: 'root'
})
export class CountryLoadService {
constructor(private http : HttpClient ) {}
// HTTP get operation to fetch the port data from static JSON
fetchCountry(){
return this.http.get("assets/data/port_data.json").pipe(map((res) => of(res)));
}
}
header.component.ts
import { Component, OnInit, EventEmitter, Output, Input } from '@angular/core';
import { CountryLoadService } from './../country-load.service';
import { HttpClient } from '@angular/common/http';
import { ArrayType } from '@angular/compiler/src/output/output_ast';
import { Observable } from 'rxjs/internal/Observable';
import { toArray } from 'rxjs/internal/operators/toArray';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
//@Input() result:string="";
@Output() changed = new EventEmitter<string>();
constructor(private countryLoadService : CountryLoadService) {}
countryData;
ngOnInit() {
this.countryLoadService.fetchCountry().subscribe(data => {
console.log(data);
console.log(this.countryData);
this.countryData = data;
console.log(this.countryData);
})
}
onChange(countryName:string){
this.changed.emit(countryName);
}
}
頭文件.component.html
<table width="100%" border="0" cellpadding="0" cellspacing="0"
height="8">
<tr>
<td width="70%" align="left" valign="middle" class="toplinks">
<app-menutab></app-menutab>
</td>
<td width="5%" align="right" valign="middle" class="toplinks">
<label class="toplinks">Load Country</label>
</td>
<td width="10%" align="right" valign="middle" class="toplinks">
<select #input1 style="width: 135px; font-family: Arial narrow; font-size: 8pt"
name="countryCode" (change)="onChange(input1.value)">
<option *ngFor="let cn of (countryData | async)">{{cn.country_name}}</option>
<!-- <input [(ngModel)]="countryData[index]" placeholder="item"> -->
</select>
</td>
</tr>
</table>
創建-tariff.component.ts
import { Component, OnInit } from '@angular/core';
import { CountryLoadService } from './../country-load.service';
import { Observable, Subject, asapScheduler, pipe, of, from,
interval, merge, fromEvent } from 'rxjs';
import { ArrayType } from '@angular/compiler/src/output/output_ast';
import { map, startWith, filter } from 'rxjs/operators';
import 'rxjs';
import { Country } from './Country'
import { concat } from 'rxjs/internal/observable/concat';
@Component({
selector: 'app-create-tariff',
templateUrl: './create-tariff.component.html',
styleUrls: ['./create-tariff.component.css']
})
export class CreateTariffComponent implements OnInit {
//jsonData : Observable<any>[] = [];
//jsonData : Country[] = [];
jsonData;
constructor(private currencyLoadService : CountryLoadService) {}
ngOnInit() {
this.currencyLoadService.fetchCountry().subscribe(data => {
console.log(typeof(data));
this.jsonData = data;
//this.jsonData = Object.entries(data).map(([type, value]) => ({type, value}));
console.log(this.jsonData);
})
}
onChanged(value:string){
if(value!='')
{
console.log('foo1111');
console.log(this.jsonData);
this.jsonData = this.jsonData.filter(res =>res.country_name.startsWith(value));
//this.jsonData = this.jsonData.map(resp => resp.filter(res => res.country_name.startsWith(value)));
//const source = from(this.jsonData);
//const ex = source.pipe(filter(res => res.country_name.starstWith(value)));
}
else{
this.currencyLoadService.fetchCountry().subscribe(
(data => {
this.jsonData = data;})
);
}
}
}
創建-tariff.component.html
<app-header (changed)="onChanged($event)"></app-header>
<span *ngFor="let item of (jsonData | async)">{{item.currency}}</span>
端口數據.json
[
{
"country_name": "Germany",
"load_port": [
"DEBRV06",
"DEBRVTM",
"DEHAMCA",
"DEHAMEK"
],
"currency": "EUR"
},
{
"country_name": "Denmark",
"load_port": [
"DKAARPT",
"DKCPHTM"
],
"currency": "DKK"
},
{
"country_name": "China",
"load_port": [
"CNIWNCT",
"CNIWNMC",
"CNNANCT",
"CNNPOYD"
],
"currency": "CNY"
}
]
當嘗試根據從 EventEmitter 收到的值進行過濾時,出現以下錯誤。
我嘗試了從互聯網上收集的不同選項,但直到現在都沒有運氣。
任何幫助將不勝感激。
ERROR TypeError: this.jsonData.filter is not a function
at CreateTariffComponent.push../src/app/create-tariff/create-tariff.component.ts.CreateTariffComponent.onChanged (create-tariff.component.ts:40)
at Object.eval [as handleEvent] (CreateTariffComponent.html:3)
at handleEvent (core.js:19628)
at callWithDebugContext (core.js:20722)
at Object.debugHandleEvent [as handleEvent] (core.js:20425)
at dispatchEvent (core.js:17077)
at core.js:18567
at SafeSubscriber.schedulerFn [as _next] (core.js:10250)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:134)
編輯 1請查看控制台日志我得到的這個 json 數據
Observable {_isScalar: true, _subscribe: ƒ, value: Array(3)}
value: Array(3)
0: {country_name: "Germany", load_port: Array(4), currency: "EUR"}
1: {country_name: "Denmark", load_port: Array(2), currency: "DKK"}
2: {country_name: "China", load_port: Array(4), currency: "CNY"}
length: 3
__proto__: Array(0)
_isScalar: true
_subscribe: ƒ (subscriber)
__proto__: Object
編輯 2這就是我在執行 toPromise() 時在控制台中得到的
ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
__zone_symbol__state: true
__zone_symbol__value: Array(3)
0: {country_name: "Germany", load_port: Array(4), currency: "EUR"}
1: {country_name: "Denmark", load_port: Array(2), currency: "DKK"}
2: {country_name: "China", load_port: Array(4), currency: "CNY"}
length: 3
__proto__: Array(0)
__proto__: Object
data = [ { "country_name": "Germany", "load_port": [ "DEBRV06", "DEBRVTM", "DEHAMCA", "DEHAMEK" ], "currency": "EUR" }, { "country_name": "Denmark", "load_port": [ "DKAARPT", "DKCPHTM" ], "currency": "DKK" }, { "country_name": "China", "load_port": [ "CNIWNCT", "CNIWNMC", "CNNANCT", "CNNPOYD" ], "currency": "CNY" } ]; value = "Germany"; var jsonData = data.filter(res =>res.country_name.startsWith(value)); console.log(jsonData)
對我來說看起來很不錯。 嘗試了解您發送的數據是否實際上是對象數組,而不是字符串或其他內容。
好吧,就像我想的那樣,您的 get 請求不正確。
fetchCountry(){
return this.http.get("assets/data/port_data.json").toPromise().then(d=>d);
}
當您收到標題組件時:
this.countryData = this.countryLoadService.fetchCountry();
this
很可能在onChanged
是不正確的。 它以某種方式編譯得很好,但在運行時它可能不是你所期望的,可能類似於MapSubscriber
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.