LoginSignup
0
1

More than 5 years have passed since last update.

別ページにsubmit

Posted at

やりたい事

・angularで作ったページから、新規タブで別ページにsubmitする
※外部サービスを別タブで開き、ログイン画面をスキップしたい

課題

・普通にcomponent側からsubmitさせると、Not Foundになる
 →Cannot POST /***/newtab...という感じのエラー

対応

・submitをリンクとして設定

<form name="gdlogin" action={{actionUrl}} method="POST">
  <input type="hidden" name="sessionid" value={{sessionId}} />
  <a href="javascript:gdlogin.submit()" id="outserve">ガンダァァァァム!!</a>
</form>

・jqueryで叩く

$('#gdlogin')[0].click();

参考にさせてもらった記事→jQueryでリンクをクリックさせたい時

リンク元

link.html
<a href="/newtab" target="_blank">別タブ</a>

リンク先コンポーネント

newtab.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

declare var $;

@Component({
  selector: 'app-newtab',
  templateUrl: './newtab.component.html',
  styleUrls: ['./newtab.component.css']
})
export class NewtabComponent implements OnInit {
  public baseurl = 'http://***/outserve/';
  public actionUrl = '';
  public sessionId = '';

  constructor(private http: HttpClient) {}

  ngOnInit() {
    // 外部サービスからセッションIDを取得する(ほんとはこんなんハードコードしない)
    const userId = 'Setsuna';
    const password = 'GN-001';

    const url =
      this.baseurl +
      'api/login.php?UserId=' +
      userId +
      '&Password=' +
      password;

    this.http.get(url).subscribe(
      res => {
        // 取得結果をformに設定
        const parsedJSON = JSON.parse(JSON.stringify(res));
        this.actionUrl = this.baseurl + 'login.php';
        this.sessionId = parsedJSON.sessionid;

        // 本当はこうしたかったけどエラーになる
        // document['gdlogin'].submit();

        // jqueryで叩く
        $('#gdlogin')[0].click();
      },
      err => {
        console.log('見つけたぞ、世界の歪みを!' + err);
      }
    );
  }
}

newtab.html

<body>
  <form name="gdlogin" action={{actionUrl}} method="POST">
    <input type="hidden" name="sessionid" value={{sessionId}} />
    <a href="javascript:gdlogin.submit()" id="outserve">ガンダァァァァム!!</a>
  </form>
</body>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1