我有一个数据服务,如下所示:
import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http/src/response';
import { environment } from '../../environments/environment';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { ICategory } from "../shared/interfaces/category.shared";
const API_URL = environment.apiUrl;
const API_Path = '/categories';
@Injectable()
export class CategoryDataService {
constructor(private _http: HttpClient) { }
public list(includes?: string): Observable<ICategory[]> {
return this._http
.get<ICategory[]>(API_URL + API_Path, { params: { includes: includes || '' } })
.catch(this.handleError);
}
private handleError(error: HttpErrorResponse) {
return Observable.throw(error);
}
}
将其注入组件并调用它可以按预期工作。但是,如果我将该方法作为 @Input 函数传递到组件中,它将失败。 这就是我在 app.component 中声明的方式:
constructor(
public categoryData: CategoryDataService
) {
}
然后我将其传递给子组件,如下所示:
<pq-button [list]="categoryData.list" (onSelect)="setCategory($event)" title="Category"></pq-button>
组件如下所示:
import { Component, Input, Output, EventEmitter, AfterViewInit } from '@angular/core';
@Component({
selector: 'pq-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.scss']
})
export class ButtonComponent implements AfterViewInit {
@Input() list: Function;
@Input() title: string;
@Output() onSelect = new EventEmitter<string>();
selected:string;
items: any[];
constructor() { }
ngAfterViewInit() {
this.list().subscribe(response => this.items = response);
}
set($event) {
this.onSelect.emit($event);
}
}
如您所见,我先寻找一种输入法,然后使用ngAfterViewInit
,我尝试调用该方法,并订阅其结果。我确实尝试过ngOnInit
,但是却遇到了与现在相同的错误,即:
未读取未定义的属性“ get” 在ButtonComponent.CategoryDataService.list
看来HttpClient
是未定义的,但我不知道为什么。
如果查看我的 app.module ,我可以看到它是这样导入的:
import { HttpClientModule } from '@angular/common/http';
,它是 imports 数组的一部分:
@NgModule({
declarations: [
AppComponent,
CategoryComponent,
CriteriaComponent,
PersonaComponent,
SelectorComponent,
ButtonComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
SharedModule
],
providers: [],
bootstrap: [AppComponent]
})
有人知道为什么这不起作用吗?
答案 0 :(得分:1)
您可能有错误的“ this”上下文。 尝试将list()函数转换为箭头函数,以保留CategoryDataService的上下文:
public list = (includes?: string): Observable<ICriteria[]> => {
return this._http
.get<ICriteria[]>(API_URL + API_Path, { params: { includes: includes || '' } })
.catch(this.handleError);
}