Angular4 注入服务 class - 调用服务方法时构造函数中的代码未完成?

Angular4 Injecting Service class - code in constructor not finished when service method called?

我正在努力进入 Angular4/5。我连接到名为 Sanity (https://www.sanity.io/) 的 CMS 服务。我遇到的问题是此服务被注入到 ProductsComponent class 并且我在组件的 ngOnInit 方法中调用该服务中的方法。但是,当我尝试使用 ng serve 命令重新编译时出现以下错误:

ERROR in src/app/sanity.service.ts(21,14): error TS2339: Property 'fetch' does not exist on type 'object'.

这是我注入服务的组件:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Query } from '@angular/core/src/metadata/di';
import { SanityService } from '../sanity.service';

@Component({
    selector: 'app-product',
    templateUrl: './products.component.html',
    styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {

    products: object[];

    constructor(private http: HttpClient, private sanityService: SanityService) { }

    ngOnInit() {

        this.sanityService.getProducts((res) => {
            this.products = res;
        });

    }

}

这里是服务代码(sanity.service.ts):

import { Injectable } from '@angular/core';
//const sanityClient = require('@sanity/client');
import * as SanityClient from '@sanity/client';

@Injectable()
export class SanityService {

    sanityClient: object;

    constructor() {
        this.sanityClient = SanityClient({
            projectId: 'someidhere',
            dataset: 'somedatabase',
            useCdn: true
        });
    }

    getProducts(callback) {
        let query = "*[_type == 'product']{ name, _id, description, price, 'imageUrl': image.asset->url }";
        this.sanityClient
            .fetch(
                query, // Query
                {} // Params (optional)
            ).then(res => {
                //console.log('5 movies: ', res)
                //this.products = res;
                callback(res);
            }).catch(err => {
                console.error('Oh no, error occured: ', err)
            });
    }



    getProductById(id, callback) {
        var query = `*[_id == '${id}']{ name, _id, description, price, 'imageUrl': image.asset->url }`;
        this.sanityClient
            .fetch(
                query, // Query
                {} // Params (optional)
            ).then(res => {
                //console.log('PRODUCT: ', res)
                //this.products = res;
                callback(res);
            }).catch(err => {
                console.error('Oh no, error occured: ', err)
            });
    }

}

我怀疑当调用 'getProducts()' 函数时,服务构造函数中 created/set 的对象尚未完成 'loading',因此 'fetch' 属性不存在错误。

我真的很困惑...有人可以帮我吗?

还有我的app.component.ts以防万一:

import { Component } from '@angular/core';
import { SanityService } from './sanity.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [SanityService]
})
export class AppComponent {
  title = 'app';

  constructor(private sanityService: SanityService) {}
}

尝试将您的 SanityClient 键入 any,或者,如果您包含键入内容,则键入 SanityClient。 Typing as an object 告诉 TypeScript 将其视为没有任何附加功能的普通对象,因此会发出此错误!

因此将 sanityClient: object 更改为 sanityClient: any 应该可以让您的应用程序编译。

您可以创建包含 fetch 方法的接口或 class 模型。

带接口:

export interface Fetch {
    fetch
}

或型号:

export class Fetch {
   fetch
}

因此,在创建一个 class 模型之后,将其导入并执行以下操作:

sanityClient: Fetch;

可以找到两者的区别here.

Consider using a class instead of an interface for services and declarables (components, directives, and pipes).

Consider using an interface for data models.