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

如何在Angular 4中集成WooCommerce API以实现商品列表展示

Hey there! Let's walk through how to integrate the WooCommerce API into your Angular 4 app and get that full product list up and running. I’ve done this a few times, so I’ll break it down into simple, actionable steps:

Step 1: Grab Your WooCommerce API Credentials

First things first, you need API keys to authenticate requests to your WooCommerce store:

  • Log into your WooCommerce admin panel, go to Settings > Advanced > REST API
  • Click Add key, fill in a description, set permissions to "Read" (since we only need to fetch products), then generate the key
  • Save the Consumer Key and Consumer Secret somewhere safe—you’ll need these later
Step 2: Set Up Dependencies in Your Angular 4 Project

We’ll use Angular’s built-in HTTP client and a library to handle OAuth 1.0a authentication (required by WooCommerce API):

  1. Make sure HttpClientModule is imported in your app.module.ts (it’s needed for HTTP requests):
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    // Your other modules (BrowserModule, etc.)
    HttpClientModule
  ]
})
export class AppModule { }
  1. Install two npm packages for OAuth handling and hashing:
npm install oauth-1.0a crypto-js --save
Step 3: Create a WooCommerce Service (For Reusable API Calls)

It’s best practice to wrap API logic in an Angular service. Create a woocommerce.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import OAuth from 'oauth-1.0a';
import { HmacSHA1 } from 'crypto-js';

@Injectable()
export class WooCommerceService {
  // Replace these with your actual credentials and store URL
  private consumerKey = 'YOUR_CONSUMER_KEY';
  private consumerSecret = 'YOUR_CONSUMER_SECRET';
  private apiBaseUrl = 'https://your-store-domain.com/wp-json/wc/v3';

  private oauthClient: OAuth;

  constructor(private http: HttpClient) {
    // Initialize OAuth client
    this.oauthClient = new OAuth({
      consumer: {
        key: this.consumerKey,
        secret: this.consumerSecret
      },
      signature_method: 'HMAC-SHA1',
      hash_function: (baseString, key) => HmacSHA1(baseString, key).toString()
    });
  }

  // Fetch full product list
  getAllProducts() {
    const apiUrl = `${this.apiBaseUrl}/products`;
    // Generate OAuth authorization headers
    const authHeaders = this.oauthClient.toHeader(
      this.oauthClient.authorize({ url: apiUrl, method: 'GET' })
    );
    // Send GET request with auth headers
    return this.http.get(apiUrl, { headers: authHeaders });
  }
}
Step 4: Build a Component to Display Products

Create a product-list.component.ts to fetch and render the products:

import { Component, OnInit } from '@angular/core';
import { WooCommerceService } from './woocommerce.service';

@Component({
  selector: 'app-product-list',
  template: `
    <div class="product-grid">
      <div *ngFor="let product of products" class="product-card">
        <h3>{{ product.name }}</h3>
        <img [src]="product.images[0]?.src" alt="{{ product.name }}" class="product-img" />
        <p class="price">{{ product.price | currency }}</p>
        <p class="desc" [innerHTML]="product.short_description"></p>
      </div>
    </div>
  `,
  styles: [`
    .product-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 20px;
      padding: 20px;
    }
    .product-card {
      border: 1px solid #eee;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .product-img {
      width: 100%;
      height: 220px;
      object-fit: cover;
      border-radius: 4px;
    }
    .price {
      font-weight: bold;
      color: #2c3e50;
    }
  `]
})
export class ProductListComponent implements OnInit {
  products: any[] = [];

  constructor(private wcService: WooCommerceService) { }

  ngOnInit() {
    this.wcService.getAllProducts().subscribe(
      (data: any[]) => {
        this.products = data;
      },
      (error) => {
        console.error('Failed to load products:', error);
        // Add user-friendly error handling here (e.g., show a toast)
      }
    );
  }
}

Don’t forget to register the component and service in app.module.ts:

import { ProductListComponent } from './product-list.component';
import { WooCommerceService } from './woocommerce.service';

@NgModule({
  declarations: [
    // Your other components
    ProductListComponent
  ],
  providers: [WooCommerceService]
})
export class AppModule { }
Step 5: Test and Troubleshoot
  • Start your Angular app with ng serve and navigate to your product list component’s route (e.g., http://localhost:4200/products)
  • CORS Issues: If you get a CORS error (super common if your Angular app and WooCommerce store are on different domains), add a proxy config:
    Create a proxy.conf.json file:
    {
      "/wp-json": {
        "target": "https://your-store-domain.com",
        "secure": true,
        "changeOrigin": true
      }
    }
    
    Then start the app with ng serve --proxy-config proxy.conf.json
  • Pagination: WooCommerce API returns 10 products by default. Add ?per_page=20 to the API URL to load more, or implement pagination logic for large product lists

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:57:10