TypeError .subscribe不是一个函数

时间:2018-09-24 21:09:22

标签: angular observable

我正在从组件中调用服务中的函数。当我尝试订阅返回的数据时,在控制台中出现以下错误:

错误TypeError:this.entityService.getEntityType(...)。subscribe不是函数

看来我的switch语句中的返回无效。如果我将此功能移回我的组件,则可以正常工作。我在做什么错了?

//组件

export class ProfileComponent implements OnInit {

pageConfigs: any;
facility: Facility;
param1: any;
entityConfig: any = {};
snapshot: RouterStateSnapshot;

constructor(
    private modelService: ModelService,
    private entityService: EntityService,
    private pageConfigsService: PageConfigsService,
    private route: ActivatedRoute,
    private router: Router
) {}

ngOnInit() {
   this.snapshot = this.router.routerState.snapshot;
    console.log('snapshot', this.snapshot);

    console.log('ngOnInit snapshot url', this.snapshot.url);

    this.entityService.getEntityType(this.snapshot.url)
    .subscribe(
        response => {
            this.param1 = response
            console.log(this.param1);
        }
    );
    console.log('endpoint', this.entityConfig.endpoint);

    this.entityService.getEntities(this.entityConfig.endpoint)
    .subscribe(
        response => {
            this.facility = this.modelService.assignModelFromResponse(this.entityConfig.model, response[0]);
            console.log('facility', this.facility);
        }
    );

    this.pageConfigsService.getPageConfigs('provider_search', 'profile')
    .subscribe(
        response => {
            this.pageConfigs = response;
        }
    );
}
}

//服务

export class EntityService {
entityConfig: any = {};

constructor(
    private firebase: AngularFireDatabase,
    private http: HttpClient
) { }

getEntities(entityType) {
    return this.http.get(`http://localhost:3000/${entityType}`);
    // return this.firebase.list('providers').valueChanges();
}

getEntityType(model) {
    switch (model) {
        case '/provider-search/profile/1?entity_type=provider':
        this.entityConfig = {
            name: 'providers',
            model: Provider,
            endpoint: 'providers'
        };
        break;
        case '/provider-search/profile/1?entity_type=facility':
        this.entityConfig = {
            name: 'facilities',
            model: Facility,
            endpoint: 'facilities'
        };
        break;
        case '/provider-search/profile/1?entity_type=pharmacy':
        this.entityConfig = {
            name: 'pharmacies',
            model: Pharmacy,
            endpoint: 'pharmacies'
        };
        break;
    }
}
}

1 个答案:

答案 0 :(得分:0)

您的getEntityType实现可能不正确,应该返回常规的字典式对象,而不是在get方法中执行赋值。为了订阅此内容,您需要将其包装成某种可观察的形式。

不过,与其替代使用,就像使用同步功能一样:

getEntityType(...) {
   return { ... }
}

this.entityConfig = this.entityService.getEntityType(this.snapshot.url);
console.log(this.entityConfig);