在Angular2中重定向到外部URL

14 浏览
0 Comments

在Angular2中重定向到外部URL

我想在某个操作之后重定向到一个外部URL。请参考我的代码:\n

this.http.get(this.apiurl+'api/insert.php?did='+this.did).subscribe(data=>{
    var jsonData = data.json();    
    let url = jsonData.urlpass;
    // 在新窗口中打开此URL,如 https://flipkart.com,并附带我的推广参数
    window.open(url ,'_blank'); 
});

\n`window.open(url ,\'_blank\')`会触发弹出窗口拦截器。\n所以我尝试了这样的方式:\n


$("#anchorID")[0].click();

\n但是这个点击事件在subscribe方法内部没有被触发。\n如果我使用以下方式:\n

var newWin = window.open();
newWin.location = url_pass;

\n会出现错误:`Cannot assign to \'location\' because it is a constant or a read-only property.`\n我想在新窗口中打开这个外部URL,并避免弹出窗口拦截器的问题。请帮忙。

0
0 Comments

问题出现的原因是在Angular2中无法直接在组件中重定向到外部URL。解决方法是在组件的HTML文件中添加一个隐藏的链接,并在组件的TS文件中调用该链接的click()方法来实现重定向。

具体的解决方法如下:

1. 在组件的HTML文件中添加一个隐藏的链接:


2. 在组件的TS文件中定义popupLink变量,并在popup()方法中调用window.open()方法来实现重定向:

@ViewChild('popupLink') popupLink: ElementRef;
popup() {
  window.open("https://www.google.com", "_blank");
}
// 在代码的某处调用popupLink.click()方法来触发重定向
popupLink.click();

然后,根据实际情况更新变量名问题,确保代码中定义的变量名与HTML中的变量名一致,这样就可以解决问题了。

希望以上方法对您有帮助!

0
0 Comments

在Angular2中,如果要在应用程序中重定向到外部URL,可以尝试以下代码:

var newWin = window.open('some_url');

这段代码使用`window.open()`方法打开一个新的浏览器窗口,并将URL设置为`some_url`。这样就可以实现从Angular2应用程序中重定向到外部URL的功能。

然而,这种方法可能会遇到一些问题。在某些情况下,浏览器可能会将该操作阻止,因为它被视为弹出式窗口,这可能会触发浏览器安全性设置。为了解决这个问题,我们可以使用Angular2的`Router`来进行重定向。

首先,需要在组件的构造函数中注入`Router`:

import { Router } from '@angular/router';
constructor(private router: Router) {}

然后,在需要进行重定向的地方,可以使用`navigate()`方法来实现重定向:

this.router.navigate(['externalRedirect', { externalUrl: 'some_url' }], { skipLocationChange: true });

这里使用了`navigate()`方法来导航到一个名为`externalRedirect`的路由,同时传递了一个包含外部URL的参数。在路由配置中,可以定义一个组件来处理这个路由:

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
  template: ''
})
export class ExternalRedirectComponent {
  constructor(private activatedRoute: ActivatedRoute, private router: Router) {
    this.activatedRoute.params.subscribe(params => {
      window.location.href = params['externalUrl'];
    });
  }
}

在这个组件中,通过订阅`activatedRoute.params`来获取传递的参数,然后使用`window.location.href`将页面重定向到外部URL。

最后,需要在路由配置中定义这个组件的路由:

import { Routes } from '@angular/router';
import { ExternalRedirectComponent } from './external-redirect.component';
const routes: Routes = [
  {
    path: 'externalRedirect',
    component: ExternalRedirectComponent
  }
];

这样,就可以通过使用`Router`和自定义的重定向组件来实现在Angular2应用程序中重定向到外部URL的功能。

0