javascript - 将函数重写为异步

标签 javascript angular typescript

如何将以下内容重写为异步函数?它在 View 上不断返回referralUrl作为未定义:

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>

推荐服务

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

最佳答案

你需要在这里实现 Observable 调用,

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

另请添加您的服务,以便我们也可以编辑您的服务返回类型。

更新2: 按如下方式更改您的服务,

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

关于javascript - 将函数重写为异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55161150/

相关文章:

angular - 服务器上取消了多个 API 调用

angular - 类型 'Observable<{}> is not assignable to type ' 可观察'

reactjs - 类型 'setTabChange' 上不存在属性 'never'。 (React hooks Typescript) 使用 ref

javascript - Typescript 循环遍历一组值

javascript - 更新按钮单击 Javascript 上的数组

javascript - 在 JavaScript 中执行 While 循环

Javascript - 为什么我不能将 style.color 设置为变量?

javascript - 在全日历中保存事件时遇到问题

json - 无法升级到 Angular4

typescript - "as string"与 toString()