我的Angular应用程序中有一个组件需要显示一个文件中的一个项目,该文件包含一个json对象数组,这些对象依赖于id(可以更改)。为了实现这一点,我有一个可以在json文件中读取的服务。该过程有效,但我需要能够将响应限制为只具有相应id的项目。我尝试在success函数中执行此操作,但我的参数提供的id值不可用。
我的代码略有清理版本如下。我不知道在哪里过滤响应只返回与变量id对应的单个项目。
json.service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable()
export class JsonService {
constructor(public http: Http) { }
getData(url): Observable<any> {
return this.http
.get(url)
.map(this.extractData);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
}
myComponent.component.ts:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { JsonService } from '../../services/json.service';
@Component({
selector: 'app-mine',
templateUrl: './my-component.component.html',
providers: [JsonService]
})
export class MyComponent implements OnInit, OnDestroy {
id:any;
data:any;
item:any;
private sub: any;
constructor(private route: ActivatedRoute, private _jsonService: JsonService) { }
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = params.id; // console.log(this.id) reports the id as expected here
let url = 'assets/data.json';
this._jsonService.getData(url).subscribe(this.resSuccess, this.resFailure, this.resComplete);
});
}
resSuccess(response) {
this.data = response;
this.data.data.forEach((obj)=>{
if(obj.id == this.id){ // console.log(this.id) shows that this.id is undefined
this.item = obj;
}
})
}
resFailure(error) {
console.log("Error happened" + error);
}
resComplete() {
console.log("the subscription is completed");
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
data.json:
[
{
"id": "hurricane",
"active": true,
"title": "Forecast a Hurricane",
"img": "/assets/hurricane.jpg"
},
{
"id": "snow",
"active": true,
"title": "Create a Snowstorm",
"img": "/assets/snow.jpg"
}
]
答案 0 :(得分:1)
问题在于您传递的是自由的未绑定函数,而不是绑定到对象的方法。
使用
this._jsonService.getData(url).subscribe(this.resSuccess.bind(this), this.resFailure.bind(this), this.resComplete.bind(this));
或
this._jsonService.getData(url).subscribe((res) => this.resSuccess(res), (err) => this.resFailure(err), () => this.resComplete());
未绑定功能无法访问this
,因为它们不属于任何对象。如果你不知道JS是如何工作的,那么小心传递对函数的引用。
答案 1 :(得分:0)
您可以使用pipable运算符。像这样:
import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import { User } from '../../../auth/shared/services/auth/auth.service';
@Component({
selector: 'app-store',
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrls: ['app-store.component.scss'],
templateUrl: 'app-store.component.html'
})
export class AppStoreComponent implements OnInit {
public radioGroupForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.radioGroupForm = this.formBuilder.group({
'model': 1
});
}
}
https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md