【问题标题】:A post request in Angular 4 doesn't work using @HostListenerAngular 4 中的 post 请求无法使用 @HostListener
【发布时间】:2018-09-29 15:53:37
【问题描述】:

主机监听器不起作用。 正在调用触发请求的函数,但未调用后期操作。 有人可以帮忙吗?

app.component.ts

@HostListener('window:beforeunload', ['$event'])
onWindowClose($event) {
    console.log('market unlocked');
    this.unlockAlias();
    return true;
}

constructor(private router: Router, private service: Adal5Service, private http : Http) {
    this.service.init(config);
}

ngOnInit() {
    this.service.handleWindowCallback();
    this.isAuthenticated = this.service.userInfo.authenticated;
}

unlockAlias() {
     const apiEndPoint = environment.baseUrl + environment.unLockAlais;
    const body = '{"uid": "' + this.service.userInfo.username + '" }';
    const headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Access-Control-Allow-Origin', '*');
    const options = new RequestOptions({ headers: headers });
    this.http
        .post(apiEndPoint,
        body, options)
        .subscribe(data => {
            console.log("unlocked");
        }, error => {
            console.log(JSON.stringify(error.json()));
        });
}}

【问题讨论】:

  • 你试过.toPromise()而不是subscribe吗?
  • 与其在 window:beforeunload 事件上使用 HostListener,不如将函数调用放在 ngOnDestroy() 上?
  • @Roysh yes .toPromise() 也不起作用

标签: angular browser


【解决方案1】:

我认为您不能在 beforeunload 中异步地 POST,因为该功能将终止,并且用户将在您的订阅解决之前离开该页面。

您可以自己拨打synchronous(阻止)呼叫,但Angular 不支持(因为这是一个坏主意),因此您必须以老式方式进行。

【讨论】:

    【解决方案2】:

    在我更改了 unlockAlias() 以返回 http 结果后它起作用了,这是一个 Observable 并在 ('window:beforeunload') 事件上订阅它。

    @HostListener('window:beforeunload', ['$event'])
    onWindowClose($event) {
        this.unlockAlias().subscribe();
    
     unlockAlias() {
        const apiEndPoint = environment.baseUrl + environment.unLockAlais;
        const body = '{"uid": "' + this.service.userInfo.username + '" }';
        const headers = new Headers({ 'Content-Type': 'application/json' });
        headers.append('Access-Control-Allow-Origin', '*');
        const options = new RequestOptions({ headers: headers });
        return this.http.post(apiEndPoint, body, options);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      相关资源
      最近更新 更多