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

Search and extract JSON data in MySQL

Currently, I am inputting JSON objects into a MySQL Database and then executing queries on them. Within the database is a table structured as follows: subjects | ----------------------------------------------- ...

What is the module system that fabric composer utilizes for its logic JavaScript files?

I am currently in the process of creating a business-network-definition for Hyperledger using Fabric (based on generator-hyperledger-fabric). Everything has been running smoothly so far, but as we move onto our Proof of Concept (PoC), a few questions have ...

Use the `fetch` method in JavaScript/TypeScript to make an API call to an IPFS URI but be prepared for potential issues like CORS restrictions, network errors, or

I am currently working on a Next.js project with TypeScript in the browser, and I need to execute the following fetch request: const tokenURIResponse = await fetch( "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg ...

`On the first date chosen, activate an event within the ngx-bootstrap daterangepicker.`

I am utilizing a date range picker with the following code: <bs-daterangepicker-inline [bsValue]='bsValue' (bsValueChange)="test()"></bs-daterangepicker-inline>. Is there a way to trigger an event when the first date is sel ...

Retrieving array-like form data in a TypeScript file

I need assistance with passing form inputs into a typescript file as an array in an ionic application. The form is located in question.page.html <details *ngFor="let product of products;"> <ion-input type="text" [(ngModel ...

The Express application appears to be unresponsive, but the data has been successfully saved to the MongoDB database. An error with the

Currently, I am delving deeper into the MERN stack and working on a straightforward CRUD application utilizing it. One of the recent additions to the app includes validators implemented through express-validator for handling requests. However, an issue ari ...

What is the best way to add 1 to a number every second with javascript?

My code seems to be functioning correctly, but I'm having trouble setting the delay and stopping the increment after a certain interval. Can someone please assist me with this? Javascript: $(document).ready(function() { var number = parseInt($(& ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

`Must have content in file input in order to be saved to MongoDB`

When attempting to save a registry in MongoDB using Node.js, it seems that the operation fails if an image is not selected. I would like the inclusion of an image in this process to be optional, rather than mandatory. router.post("/", upload.single("image" ...

Can the PrimeNG p-fileUpload component be configured to launch from a specific directory?

Utilizing the PrimeNG p-fileUpload component for file uploads. Looking to customize the default folder that opens when the select file button is clicked. Would like it to open in a specific location such as Desktop or Videos. Is there a method to achieve ...

Typescript -> In a React Native project, the type of 'value' is classified as 'unknown'

While working on converting a JS file to TS within my react native project, I encountered an issue that I am struggling to resolve. The problem arises when the value['flag'] is displaying an error message stating 'value' is of type &apo ...

What is the best way to arrange the keys within a nested object in JavaScript?

Question: { "foo": "bar", "bar": "baz", "baz" : { "nestedKey": "foo" } } In order to sign this request using the Hmac512 algorithm, I must first stringify the object. I am concerned that if the key order is not preserved, the generated signature on the ...

Is there a way to modify the spacing between labels and text in the TextBox MUI component while using custom label sizes?

I've customized a material ui TextField component by increasing the font size of the label. However, I'm facing an issue where the gap in the border for the label remains unchanged despite the larger text size. I couldn't find any solution ...

Although Angular allows for CSS to be added in DevTools, it seems to be ineffective when included directly in

Looking to set a maximum length for ellipsis on multiline text using CSS, I tried the following: .body { overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; } However, this approach did not work. Interesti ...

How to programmatically close an Angular 5 Modal

In my current project, I am working with Angular 5. One of the functionalities I have implemented is a modal window. The HTML structure for this modal looks like this: <div class="add-popup modal fade" #noteModal id="noteModal" tabindex="-1" role="dia ...

Discovering the power of Angular: Leveraging nativeElement to enhance your click handlers

Perhaps just a "stylish" yet effective solution... Here's what I have that is functional: // Template <div *ngFor="let media of period.media"> . . . <button #btn (click)="onDeleteClick(btn)" [attr.media-id]="media.ID"> ...

Displaying API response array object in React application

Currently, I am attempting to retrieve information from an API, parse the response content, and then display it in a loop. However, I have encountered a warning message: webpackHotDevClient.js:138 ./src/App.js Line 20: Expected an assignment or function ...

How can I prevent SweetAlert from automatically focusing when it first opens?

I recently integrated SweetAlert into my project and customized the buttons like this: swal("A wild Pikachu appeared! What do you want to do?", { buttons: { cancel: "Run away!", catch: { text: "Throw Pokéball!", value: "catch", ...

Navigational module and wildcard for routes not located

I have my routing configuration structured as follows: app-routing const routes: Routes = [ { path: 'login', loadChildren: 'app/modules/auth/auth.module#AuthModule' }, { path: '', redirectTo: 'dash ...

The canvas loadFromJson function fails to implement the font-family property

I have implemented the following code to display Google font and update the canvas: /* on change of font, load the preview and update the canvas */ $('#font').on('change', function () { $('.font_preview').show ...