【发布时间】:2019-09-25 15:34:03
【问题描述】:
在我的 Ionic 4 angular 8 应用程序中,我使用 chrome 扩展来返回选项卡 URL。我在服务文件中定义的函数中获取选项卡 URL 值,但是当在 ngOnInit() 中调用服务时,我变得未定义。请帮我解决这个问题。
我希望 URL 值显示在ngOnInit()
内部服务文件
async chromeCall() {
try {
const results = await chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { from: 'popup', subject: 'DOMInfo' }, (response) => {
console.info("Tab ID:", tabs[0].id);
this.CurrentPgUrl = response.webPgURL;
console.log(this.CurrentPgUrl);//geting value here
return this.CurrentPgUrl;
});
});
}
catch (err) {
console.log(err);
console.log("comes to error ");
}
}
内部ngOnit()
ngOnInit(){
this.apiService.chromeCall()
.then(result => {
this.url=result;
console.log(this.url)//value undefined
)};
【问题讨论】:
-
你的意思是
this.CurrentPgUrl是undefined吗? -
我建议不要使用
function(tabs) {...},而是使用(tabs) => {...}。这是因为function创建了一个新的作用域,所以this不再指代相同的东西了。 -
我不确定这是您遇到的问题,但可能是
-
是的,我在 ngOnit() 中需要 this.currentPgurl。但现在我越来越不确定
-
您是否尝试使用粗箭头 (
=>) 而不是function?
标签: angular typescript promise ionic4 angular8