如何将以下内容重写为异步函数?它在 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/