methuselah
methuselah

Reputation: 13216

Rewriting function to be asynchrononous

How do I rewrite the following as an async function? It keeps returning referralUrl on the view as undefined:

controller

  createReferralUrls() {
    this.referralUrl = 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;
    }
  }

Upvotes: 0

Views: 69

Answers (2)

rcanpahali
rcanpahali

Reputation: 2643

You need to implement Observable call here,

    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;        
        }
       );      
      }

Please also add your service, so we can edit your service returning type as well.

Update2: Change your service as below,

  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) });
    }
  }

Upvotes: 1

arpit sharma
arpit sharma

Reputation: 405

Please change your input like this
<input type="text" class="form-control" placeholder="" [value]="referralUrl" readonly>

Upvotes: 0

Related Questions