Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined:

controller

  async createReferralUrls() {
    this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referralId);
    this.campaignMessage = 'Sign up here: ' + this.referralUrl + '.';
    this.facebookShareUrl = 'http://www.facebook.com/sharer/sharer.php?u=' + this.referralUrl;
    this.whatsappShareUrl = 'https://wa.me/?text=' + this.campaignMessage;
    this.twitterShareUrl = 'https://twitter.com/intent/tweet?text=' + this.campaignMessage;
    this.emailShareUrl = 'mailto:?subject=Welcome to our site!&body=' + this.campaignMessage;
  }

html

<input type="text" class="form-control" placeholder="" value="{{ referralUrl }}" readonly>

referralService

  generateReferralUrl(referralId) {
    if (location.host === 'localhost:4200') {
      return 'localhost:4200/invite/' + referralId;
    } else if (location.host === 'myapp.herokuapp.com') {
      return 'myapp.herokuapp.com/invite/' + referralId;
    } else if (location.host === 'myapp.com') {
      return 'myapp.com/invite/' + referralId;
    }
  }

Answer №1

Utilize the Observable method in this section,

    createReferralUrls() {
       this.referralService.generateReferralUrl(this.userData.referralId)
        .subscribe(
         (res)=>{        
            this.campaignMessage = 'Sign up here: ' + res + '.';
            this.facebookShareUrl = 'http://www.facebook.com/sharer/sharer.php?u=' + res;
            this.whatsappShareUrl = 'https://wa.me/?text=' + this.campaignMessage;
            this.twitterShareUrl = 'https://twitter.com/intent/tweet?text=' + this.campaignMessage;
            this.emailShareUrl = 'mailto:?subject=Welcome to our site!&body=' + this.campaignMessage;        
        }
       );      
      }

Additionally, include your service for modifying the returning type of your service.

Update2: Revise your service as follows,

  generateReferralUrl(referralId) {
    if (location.host === 'localhost:4200') {
      return Observable.create((observer) => { observer.next('localhost:4200/invite/' + referralId) });
    } else if (location.host === 'myapp.herokuapp.com') {
      return Observable.create((observer) => { observer.next('myapp.herokuapp.com/invite/' + referralId) });
    } else if (location.host === 'myapp.com') {
      return Observable.create((observer) => { observer.next('myapp.com/invite/' + referralId) });
    }
  }

Answer №2

To modify your entry, follow this format

<input type="text" class="form-control" placeholder="" [value]="referralUrl" readonly>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why Bootstrap 4 collapse feature is not functioning correctly within a ReactJS map component?

I am currently working on a project that requires implementing a collapse feature. The idea is to display all available content when the user clicks the Read More button (which is functioning as intended for collapsing). However, I am facing an issue where ...

What is the best way to modify specific data retrieved from an API using Angular?

After successfully listing some data from an API using ngFor, I am facing an issue with editing the data. Whenever I click the edit button, it edits the entire data instead of just the specific row. Below is the code snippet for reference: HTML <table ...

Transferring extra data from jQuery autocomplete to a PHP script

Hey there! I'm wondering if it's possible to pass extra parameters from jQuery autocomplete to a PHP page, which would then use them to query a database and return the results. While I know how to send the typed term from the input box, I'd ...

Leaflet setStyle changes are effective when applied through the console but do not reflect in the actual

I currently have a map with around 1000 polygons that I am loading onto it. My goal is to color these polygons based on a specific property value. The code snippet below showcases my approach, but the results are not as expected. mapLayerFieldGrid = new L ...

Add items to a new array with a property set to true, if they are present in the original array

Could someone assist me with the following situation? I need an array of strings. A function is required to map the array of strings, assigning each element a name and key, while also adding another object "checked: false". Another function should take t ...

Issues arise when attempting to connect NgRx Angular application with Redux DevTools

Currently, I am following a tutorial to learn about ngRx Entity. However, I am facing an issue where my Redux dev tools are not indicating that they are active in the app using Redux. Additionally, the data I expect to see in the dev tools is not showing u ...

Avoiding useCallback from being called unnecessarily when in conjunction with useEffect (and ensuring compliance with eslint-plugin-react-hooks)

I encountered a scenario where a page needs to call the same fetch function on initial render and when a button is clicked. Here is a snippet of the code (reference: https://stackblitz.com/edit/stackoverflow-question-bink-62951987?file=index.tsx): import ...

Can Typescript Be Integrated into an AngularJS Application?

I have been thinking about the optimal timing and scenario to implement Typescript in an AngularJS project. While I have come across examples of TS being used in a Node, Express, Mongo backend, I am particularly intrigued by how well TS integrates with A ...

The error message "The type 'DynamicModule' from Nest.js cannot be assigned to the type 'ForwardReference' within the nest-modules/mailer" was encountered during development

Recently, I decided to enhance my Nest.js application by integrating the MailerModule. I thought of using the helpful guide provided at this link: Acting on this idea, I went ahead and performed the following steps: To start with, I executed the command ...

Tips for triggering animation only when the element is in the viewport

I'm currently developing in React and facing a challenge where I need to trigger a fade animation for an element only when it becomes visible on the screen. The issue is that right now, the animation plays as soon as the page loads, which defeats the ...

Differences between $.ajaxPrefilter() and $.ajaxSetup() in jQuery Ajax

During my exploration of ajax in jQuery, I encountered two terms: $.ajaxPrefilter() and $.ajaxSetup(). It seems that both of these terms are related to making modifications to AJAX operations before they are executed or called by $.ajax(). Could someone p ...

Alignment of content layout across two wrapper elements

My goal is to achieve a specific layout where each pair of cards in a two-column layout is aligned based on the card with the largest content. Both cards share the same content layout and CSS. If you have any ideas or implementations that could help me ac ...

Ways to correct inverted text in live syntax highlighting using javascript

My coding script has a highlighting feature for keywords, but unfortunately, it is causing some unwanted effects like reversing and mixing up the text. I am seeking assistance to fix this issue, whether it be by un-reversing the text, moving the cursor to ...

Adjustable div height: reduce until reaching a certain point and then begin expanding once more

Incorporating a hero section to display content is my current approach. The design adapts responsively utilizing the padding-bottom percentage strategy, along with an inner container that is absolutely positioned for central alignment of the content. The ...

Save the environment value within Vue when the app starts up

When working with a basic web app created using VueJS, the application makes an API call that returns an object containing the environment name. For instance: https://appsdev/mysimpleapp/api/environment returns {"applicationName":"My S ...

I am experiencing an issue where the mat-header-cell components are not appearing after navigating

After initially loading the page, mat-header-cell displays fine. However, upon navigating to a second page, refreshing it in the browser, and then returning to the original page, the mat-header-cell is no longer visible. It only reappears after manually re ...

performing resolver when needed in angular version 5

I have been working on a project using Angular and recently updated it from version 4.2 to Angular 5. Although I haven't utilized any new features introduced in Angular 5 yet. My current task involves executing a resolver on a specific route when a c ...

Troubleshooting React and Material-UI: Adjusting <slider> component for use with personalized data

I am facing a challenge with using the Material-UI slider to showcase API data. The unique aspect here is that the slider is intended for displaying data without any interactivity. Encountering an error message: Slider.js:91 Uncaught TypeError: nearest.to ...

What is the best method for custom Validators to access specific Values on a Form?

Seeking guidance on implementing custom validation in my Angular app. Specifically, I need to validate an email address input against a local array called emails. The challenge is that the emails data comes from an API call and is initially empty when the ...

In Typescript, object strings can be enforced to be used from the parent object similar to

I am currently developing an API wrapper for a lower level library that utilizes enums to map human readable keys to internal values. In order to enhance security, I want to only use the enum keys and not the underlying values in any logging or other funct ...