我正在尝试进入 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) {}
}