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

在Angular 5中实现推送通知:接收后调用PHP接口方案咨询

How to Listen for OneSignal Notifications in Angular 5 and Trigger a PHP Backend API

Hey there! Since you've already got OneSignal set up in your Angular 5 app, let's walk through how to detect when a notification is received and immediately call your PHP backend. Here's a step-by-step approach that’s easy to implement:

1. Declare the Global OneSignal Variable

Angular might not recognize the global OneSignal object injected by the OneSignal script, so first add this declaration at the top of your component or service file to avoid TypeScript errors:

declare var OneSignal: any;

2. Set Up Event Listeners

OneSignal provides two key events for your use case:

  • notificationReceived: Triggers when the browser receives the notification (even if the app is in the background and the notification doesn’t pop up)
  • notificationDisplay: Triggers when the notification actually appears on the user’s screen

Wrap these listeners inside OneSignal.push() to ensure they run only after the OneSignal SDK is fully initialized. Here’s a complete example using an Angular component:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

declare var OneSignal: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    OneSignal.push(() => {
      // Listen for when a notification is received
      OneSignal.on('notificationReceived', (notification: any) => {
        console.log('Notification received:', notification);
        // Call your PHP backend right away
        this.notifyBackend(notification);
      });

      // Optional: Listen for when the notification is displayed to the user
      OneSignal.on('notificationDisplay', (notification: any) => {
        console.log('Notification shown to user:', notification);
        // Uncomment below if you want to trigger the API here too
        // this.notifyBackend(notification);
      });
    });
  }

  private notifyBackend(notification: any): void {
    // Replace with your actual PHP API endpoint
    const apiEndpoint = 'https://your-domain.com/api/notification-received';

    // Prepare payload with relevant notification data
    const payload = {
      notification_id: notification.payload.notificationID,
      title: notification.payload.title,
      body: notification.payload.body,
      // Add any other data your backend needs (e.g., user ID)
    };

    // Send POST request to PHP backend
    this.http.post(apiEndpoint, payload)
      .subscribe({
        next: (response) => console.log('Backend notified successfully:', response),
        error: (err) => console.error('Failed to notify backend:', err)
      });
  }
}

3. Key Things to Keep in Mind

  • CORS Configuration: Make sure your PHP backend allows cross-origin requests from your Angular app’s domain. You can add headers like Access-Control-Allow-Origin: * (or your specific domain) in your PHP code to enable this.
  • Notification Permissions: These events will only fire if the user has granted notification permissions to your app. Double-check that you’ve implemented the permission request flow correctly.
  • Background Behavior: notificationDisplay might not trigger if the browser is in the background (depends on browser settings). Use notificationReceived if you need to capture the event regardless of the app’s state.
  • Service Reusability: For cleaner code, consider moving this logic into an Angular service instead of a component. This lets you reuse the notification handling across multiple parts of your app.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:42:05