Winwheel.js回调函数在Angular框架中无法正常工作
Hey there! Let's troubleshoot why your Winwheel callback isn't working in your Angular component—this is a super common issue when mixing external libraries with Angular's component context, so let's break down the fixes step by step:
this Context Mismatch The biggest culprit here is usually lost component context. When you pass a regular function as a Winwheel callback, this inside that function will point to the Winwheel instance itself, not your Angular component. Here are two easy fixes:
Option A: Use Arrow Functions
Arrow functions preserve the parent context, so this will correctly reference your component:
initWheel() { this.wheel = new Winwheel({ 'numSegments': 8, 'outerRadius': 155, 'innerRadius': 150, 'pointerAngle': 90, 'textFontSize': 0, 'segments': [ { 'fillStyle': '#eae56f', 'text': 'Prize 1' }, { 'fillStyle': '#89f26e', 'text': 'Prize 2' }, // Add your other segments here ], // Use arrow function for the callback animationFinished: () => { this.wheelSpinning = false; // Now this refers to your component! const winningSegment = this.wheel.getIndicatedSegment(); console.log(`You won: ${winningSegment.text}`); } }); }
Option B: Bind the Function to Your Component
If you prefer using regular functions, bind the callback to your component's this in the constructor:
constructor() { // Bind the callback to preserve component context this.onWheelAnimationEnd = this.onWheelAnimationEnd.bind(this); } onWheelAnimationEnd() { this.wheelSpinning = false; const winningSegment = this.wheel.getIndicatedSegment(); alert(`Winner: ${winningSegment.text}`); } initWheel() { this.wheel = new Winwheel({ // ... your existing config animationFinished: this.onWheelAnimationEnd }); }
Make sure Winwheel is available when your component initializes:
- Add Winwheel's script to your
angular.jsonunderarchitect > build > options > scripts:"scripts": [ "path/to/your/winwheel.min.js" ] - Add a TypeScript declaration at the top of your component to avoid "Winwheel is not defined" errors:
import { Component, AfterViewInit } from '@angular/core'; declare var Winwheel: any; // Declare Winwheel as a global variable @Component({ selector: 'app-wheel', templateUrl: './wheel.component.html', styleUrls: ['./wheel.component.css'] }) export class WheelComponent implements AfterViewInit { // ... your component code }
Double-check that you're using the correct Winwheel callback names (like animationFinished for post-spin logic) and that your spin trigger function properly manages the wheelSpinning state:
startSpin() { if (!this.wheelSpinning) { this.wheelSpinning = true; this.wheel.startAnimation(); // This will trigger the animationFinished callback } }
Start with fixing the this context first—it's the most frequent fix for this exact issue. Once that's sorted, confirm Winwheel is loaded correctly and your callback logic is tied to the right Winwheel events.
内容的提问来源于stack exchange,提问作者ali

