Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

Event listener "message", based on event name making an API call with promise in angularJs, javascript

I am trying to listen to a "message", by adding an event listener and based on an eventName property in the event data which is coming as string, I need to make a promise and fetch some data from an API.
But this promise call is not happening.

Sample data:

event.data = `{"eventName":"modal:open","eventData":{"state":"redeem","stateParams":{"rewardTitle":"Lab Coat Live - 35% Discount","rewardId":550288},"width":700,"src":"https://qa-crowdtwist.thermofisher.com/widgets/t/redeem/550288/#2"},"direction":"up","widgetId":13324,"version":2}`

If "eventName": "reward:redeemed" then I need to make the API call. But the promise is not executing neither throwing any error. Am I doing something wrong or is there any other procedure to make this promise to work?

const event = new Event("message");
$window.addEventListener(event.type, function (event) {
    if(typeof event.data === "string"){
        var data = event.data;
        var redeemed = false;
        if(data.indexOf("reward:redeemed")){
            redeemed = true;
        }
    }                
    if(redeemed){
        dataService.getUserPoints();                    
    }
}, false);
$window.dispatchEvent(event);
question from:https://stackoverflow.com/questions/66051994/event-listener-message-based-on-event-name-making-an-api-call-with-promise-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Keep in mind that the AngularJS framework modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

Consider using the AngularJS event propagation mechanism. Scopes can propagate events in similar fashion to DOM events. The event can be broadcasted to the scope children or emitted to scope parents.

For more information, see


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...