繁体   English   中英

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

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

我正在尝试进入Angular4 / 5。 我已连接到名为Sanity( https://www.sanity.io/ )的CMS服务。 我遇到的问题是,此服务已注入到ProductsComponent类,并且我在组件的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()”函数时,在服务的构造函数中创建/设置的对象尚未完成“加载”,因此,“ 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 键入为对象会告诉TypeScript将其视为没有任何附加功能的普通对象,因此会发出此错误!

因此,将sanityClient: object更改为sanityClient: any sanityClient: object都应允许您的应用程序进行编译。

您可以创建Interface或包含fetch方法的类Model。

带界面:

export interface Fetch {
    fetch
}

或搭配型号:

export class Fetch {
   fetch
}

因此,例如,在创建类模型之后,将其导入并执行以下操作:

sanityClient: Fetch;

两者的区别可以在这里找到。

考虑为服务和可声明项(组件,指令和管道)使用类而不是接口。

考虑将接口用于数据模型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM