Angular
This guide provides a comprehensive, step-by-step process to create your first custom widget using Angular and the TakeProfit Widget SDK (version 0.2.3). By following this guide, you’ll set up an Angular project, integrate the SDK, configure necessary security headers, and implement basic functionalities to interact with the TakeProfit platform. This example serves as a foundation for building more complex and feature-rich widgets tailored to your specific needs.
Prerequisites
Before you begin, ensure you have the following:
- Node.js: Version 14 or higher. Download from Node.js Official Website.
- npm or Yarn: Package managers that come with Node.js.
- Angular CLI: Install globally using
npm install -g @angular/cli
. - Code Editor: Such as Visual Studio Code.
- Basic Knowledge: Familiarity with JavaScript, TypeScript, and Angular.
- Access to TakeProfit Platform: For widget integration and testing.
Set Up Your Angular Project
-
Create a New Angular App
Use Angular CLI to bootstrap a new Angular project. Open your terminal and run:
Follow the prompts to set up your project. For this guide, it’s recommended to select the following options:
- Would you like to add Angular routing?
Yes
- Which stylesheet format would you like to use?
CSS
(or your preferred choice)
- Would you like to add Angular routing?
-
Start the Development Server
Verify that your Angular app is set up correctly by starting the development server:
This will run your app at
http://localhost:4200/
.
Install the TakeProfit Widget SDK
-
Install the SDK
Integrate the TakeProfit Widget SDK into your Angular project by installing it via npm or Yarn:
Or with Yarn:
-
Verify Installation
Check your
package.json
to ensuretakeprofit-widget-sdk
is listed underdependencies
:
Configure Security Headers
To ensure that your widget can be embedded securely within the TakeProfit platform, you need to configure specific HTTP headers. Since Angular applications are typically served using static servers, you’ll need to set up a simple Express server to serve your widget with the necessary headers.
-
Install Express and CORS
Install Express and CORS to create a server that can set custom headers:
-
Create the Server File
Create a new file named
server.js
in the root of your project:Open
server.js
and add the following code:Explanation:
- CORS Middleware: Allows requests only from
https://takeprofit.com
. - Security Headers: Sets
X-Frame-Options
andContent-Security-Policy
to allow embedding only fromhttps://takeprofit.com
. - Static Files: Serves the Angular app from the
dist/my-tp-widget
directory. - Fallback to
index.html
: Ensures that Angular’s routing works correctly.
- CORS Middleware: Allows requests only from
-
Build the Angular App
Before running the server, build your Angular application:
This will generate the production build in the
dist/my-tp-widget
directory.
Initialize the SDK in Your Project
-
Create an SDK Initialization Service
Generate a new service to handle SDK initialization and cleanup:
This will create
tp-widget-sdk.service.ts
in thesrc/app/services
directory. -
Implement the Service
Open
src/app/services/tp-widget-sdk.service.ts
and add the following code:Explanation:
TpWidgetSdkService
: Provides methods to initialize, cleanup, and interact with the TakeProfit Widget SDK.- Type Definitions: Defines necessary TypeScript interfaces for type safety.
-
Provide the Service Globally
The service is already provided in the root injector via the
@Injectable
decorator, so no additional configuration is needed.
Create Your First Widget Component
-
Generate a New Component
Create a new component for your widget:
This will create
widget.component.ts
,widget.component.html
, and related files in thesrc/app/components/widget
directory. -
Implement the Widget Component
Open
src/app/components/widget/widget.component.ts
and add the following code:Important Corrections:
- Conditional Checks: Updated
if (result.isSuccessful)
toif (result.payload.isSuccessful)
to correctly access theisSuccessful
property within thepayload
. - Error Messages: Updated
${result.error}
to${result.payload.error}
to correctly access theerror
message within thepayload
.
Explanation:
- Lifecycle Hooks:
ngOnInit
: Initializes the SDK and subscribes to widget and channel state changes.ngOnDestroy
: Unsubscribes from state changes and cleans up the SDK.
- Methods:
handleWidgetChange
: Logs widget state updates.handleChannelChange
: Logs channel state updates.changeSecurity
: Requests a security change and handles the response.addMenuItem
: Adds a new menu item labeled “Refresh Data”.updateMenuItem
: Updates the existing menu item’s label to “Refresh Data (Updated)”.removeMenuItem
: Removes the menu item and resetsmenuItemId
.
- Conditional Checks: Updated
-
Design the Widget Template
Open
src/app/components/widget/widget.component.html
and add the following code: -
Style the Widget
Open
src/app/components/widget/widget.component.css
and add the following styles:Explanation:
- Centers the widget with padding, background color, and box shadow.
- Styles buttons for better user experience.
- Disables buttons appropriately when no menu item is present.
-
Include the Widget Component in Your App
Open
src/app/app.component.html
and replace its content with the widget component selector:
Manage Widget State and Interactions
-
Handle Widget and Channel State Changes
The widget component (
widget.component.ts
) already includes methods to handle widget and channel state changes (handleWidgetChange
andhandleChannelChange
). These methods log the updated states to the console. You can expand these methods to perform additional actions based on state changes as needed. -
Implement Additional Interactions
Depending on your widget’s requirements, you can add more functionalities such as updating menu items, handling user inputs, and integrating real-time data feeds. The current implementation includes buttons to change security and manage menu items, demonstrating basic interactions with the SDK.
Add Menu Items
Enhance your widget by adding custom menu items to the widget header.
-
Implement Menu Item Functions in
widget.component.ts
The menu item functions are already implemented in Step 5. Here’s a recap:
-
Add Menu Item
-
Update Menu Item
-
Remove Menu Item
Explanation:
- Add Menu Item: Adds a new menu item labeled “Refresh Data” to the widget header. Upon successful addition, stores the
menuItemId
. - Update Menu Item: Updates the existing menu item’s label to “Refresh Data (Updated)”.
- Remove Menu Item: Removes the menu item using the stored
menuItemId
and resets it.
-
-
Ensure Unique Menu Item IDs
When adding multiple menu items, ensure each has a unique
menuItemId
to prevent conflicts. In this example, we’re managing a single menu item, but you can extend this logic to handle multiple items as needed.
Test Your Widget Locally
-
Start the Server
Ensure your Express server is running to serve the widget with the configured headers:
Your widget will be accessible at
http://localhost:8080
. -
Configure Local Storage for Testing
To simulate the widget’s presence on the TakeProfit platform, configure local storage in your browser:
-
Open the TakeProfit Platform: Navigate to the TakeProfit platform in your browser.
-
Open Developer Console: Press
F12
orCtrl+Shift+I
to open the developer tools. -
Set Local Storage Entry:
Note:
- Replace
'http://localhost:8080'
with your actual widget URL if different. - Provide a valid
imageUrl
for the widget icon.
- Replace
-
-
Reload the TakeProfit Platform
Refresh the TakeProfit platform page. Your Angular widget should now appear in the widget panel, allowing you to add it to the dashboard and interact with its functionalities.
-
Verify Functionality
- Security Change: Click on the “Set Security” buttons and observe the console logs for successful changes.
- Menu Items: Add the “Refresh Data” menu item and click it to see the corresponding console log. Test updating and removing the menu item to ensure they function as expected.
Deploy Your Widget
Once testing is successful, deploy your widget to a live environment.
-
Choose a Hosting Service
Select a hosting service that can serve Angular applications and supports custom HTTP headers. Some popular options include:
- Vercel
- Netlify
- AWS Amplify
- Heroku
-
Prepare Your Files for Deployment
Ensure all your files (
dist/my-tp-widget
,server.js
, etc.) are correctly set up and that your server configuration (server.js
) is compatible with your hosting service. -
Deploy to Heroku (Example)
Here’s how to deploy your widget to Heroku with the necessary headers:
-
Install Heroku CLI
-
Log in to Heroku
-
Create a New Heroku App
Replace
your-app-name
with your desired app name. -
Set Buildpacks
Heroku needs to know how to build your app. Set the Node.js buildpack:
-
Add a
Procfile
Create a
Procfile
in the root of your project to specify how to run your app:Add the following line to
Procfile
: -
Commit Your Changes
-
Deploy to Heroku
Note: If you’re using the
main
branch, usegit push heroku main
instead.
-
-
Update Local Storage Configuration
After deployment, update the
iframeUrl
in the TakeProfit platform’s local storage to point to your deployed widget’s URL: -
Final Testing
Reload the TakeProfit platform and verify that your deployed widget functions correctly in the live environment. Test all functionalities, including security changes and menu item interactions, to ensure seamless integration.
Best Practices
-
Secure Communication: Always serve your widget over HTTPS to ensure secure communication with the TakeProfit platform.
-
Unique Identifiers: Ensure that
requestId
andmenuItemId
are unique to prevent conflicts. -
Subscription Management: Always unsubscribe from state changes when they’re no longer needed to prevent memory leaks.
-
Error Handling: Implement robust error handling for all asynchronous operations to enhance user experience.
-
Performance Optimization: Limit the number of active subscriptions and avoid unnecessary state updates to maintain optimal performance.
-
Code Documentation: Keep your code well-documented to facilitate maintenance and future enhancements.
-
Responsive Design: Ensure your widget is responsive and functions seamlessly across different devices and screen sizes.
Next Steps
Congratulations! You’ve successfully created and integrated your first widget using Angular and the TakeProfit Widget SDK (version 0.2.3). To further enhance your widget, consider the following:
- Explore Advanced SDK Features: Refer to the SDK Reference to utilize all available methods and message types.
- Implement Real-Time Data: Integrate real-time data feeds to provide dynamic and up-to-date information within your widget.
- Customize the UI: Enhance the user interface with additional Angular components and styling to improve user engagement.
- Add More Interactions: Implement more interactive features like custom events, notifications, and user preferences.
- Optimize: Ensure your widget is responsive and functions seamlessly across different devices and screen sizes.
- Security Enhancements: Implement additional security measures to safeguard data and ensure secure communication.
For comprehensive details, refer to the SDK Reference and other documentation resources provided by the TakeProfit Widget SDK.
Troubleshooting
If you encounter issues while setting up or using the TakeProfit Widget SDK, consider the following solutions:
-
SDK Not Connecting
- Check Origins: Ensure that your widget’s domain is allowed and matches the trusted origins (
takeprofit.com
). - Network Issues: Verify that there are no network restrictions or firewall rules blocking communication.
- Check Origins: Ensure that your widget’s domain is allowed and matches the trusted origins (
-
Menu Items Not Appearing
- Local Storage Configuration: Double-check the
iframeUrl
and ensure it points to the correct widget URL. - SDK Initialization: Ensure that
TPWidgetSDK.connect()
andTPWidgetSDK.hideLoader()
are called successfully.
- Local Storage Configuration: Double-check the
-
Security Change Fails
- Valid Security ID: Ensure that the
securityID
you are requesting is valid and recognized by the platform. - Error Handling: Check the console for error messages to understand why the request failed.
- Valid Security ID: Ensure that the
-
Unhandled Promise Rejections
- Implement
.catch
Blocks: Ensure that all asynchronous SDK methods have proper error handling using.catch
to manage rejected promises.
- Implement
-
Performance Issues
- Optimize Subscriptions: Limit the number of active subscriptions and avoid unnecessary state updates.
- Efficient Rendering: Ensure that your Angular components are optimized to prevent unnecessary re-renders.
For persistent issues, refer to the Support and Resources section or contact the support team for assistance.
Additional Resources
- Installation Guide: Detailed instructions for installing the SDK.
- SDK Reference: Comprehensive documentation of all available methods, interfaces, and message types.
- Creating Your First Widget: A practical guide to building and testing a basic widget.
- Angular Documentation: Official Angular documentation for deeper understanding.
- TypeScript Documentation: Learn more about TypeScript for enhanced type safety.
- Express Documentation: Official Express documentation for server setup.
- Content Security Policy (CSP) Documentation: Learn more about CSP for enhancing security.
- HTTP Headers Documentation: Understand various HTTP headers for better configuration.