You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular4注入Service类问题:调用方法时构造函数未完成且fetch属性不存在

Fixing "Property 'fetch' does not exist on type 'object'" in Angular with Sanity

Hey there, let's get this TypeScript error sorted out for your Angular app using Sanity! That TS2339 error is telling you TypeScript doesn't recognize the fetch method on the object you're working with—this almost always comes down to missing or incorrect type definitions for your Sanity client.

Here's how to fix it step by step:

1. Use Sanity's Official Type Definitions

The @sanity/client package comes with built-in TypeScript types, so make sure you're leveraging them properly:

  • First, import the SanityClient type from the package alongside the client initializer.
  • Explicitly type your service's Sanity client property with SanityClient instead of object.

Example corrected sanity.service.ts:

import { Injectable } from '@angular/core';
import { SanityClient, sanityClient } from '@sanity/client';

@Injectable({ providedIn: 'root' })
export class SanityService {
  // Explicitly type the client as SanityClient
  private sanityClient: SanityClient;

  constructor() {
    // Initialize the client with your project config
    this.sanityClient = sanityClient({
      projectId: 'your-project-id',
      dataset: 'your-dataset-name',
      useCdn: true // Adjust based on your needs
    });
  }

  // Now fetch will be recognized correctly
  async getProducts() {
    return this.sanityClient.fetch('*[_type == "product"]');
  }
}

2. Temporary Fix: Type Assertion (If You Need It Fast)

If you're in a pinch and need a quick workaround (note: this disables TypeScript's type checking for that call, so use sparingly), you can use a type assertion to tell TypeScript your object has the fetch method:

async getProducts() {
  return (this.sanityClient as any).fetch('*[_type == "product"]');
}

This gets rid of the error immediately, but it's better to use the official types long-term to catch bugs early.

3. Verify Your Client Initialization

Double-check that you're initializing the Sanity client correctly. If you pass invalid config or use an outdated initialization method, you might end up with a generic object instead of the proper client instance. Ensure your config includes required fields like projectId and dataset, and adjust auth settings if your project requires them.

4. Update Your Sanity Package

If you're using an older version of @sanity/client, it might not have complete TypeScript support. Run this command in your project root to update:

npm install @sanity/client@latest

Once you make these changes, run ng serve again—your error should be gone, and TypeScript will properly recognize the fetch method on your Sanity client.

内容的提问来源于stack exchange,提问作者Pippy Longstocking

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:27:15