0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

javascript2

Posted at

angularではwebAPIをそのまま呼び出すことができる

fetchAPIを使う例

  async fetchByFetch(){
    const response = await fetch(this.jsonFileUrl, {method: 'GET'});
    if (!response.ok) {
      console.error('データの取得中にエラーが発生しました:', response.statusText);
      return;
    }

    const data: Array<OptionItem> = await response.json();
    this.videoFiles = data;
    console.log('取得したデータ:', this.videoFiles);
    this.safeVideoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.backendUrl + this.videoFiles[0].path);

  }

https://angular.jp/guide/http/making-requests#fetching-json-data
HTTPClientはObsevableを構築して返す
HTTPのgetの場合このObservaleは単一のレスポンスを返すので
nextで処理しても問題ない
複数回に分けて送られるデータを処理するコード

   const ovservable1 = this.http.get(this.largeDataUrl, { responseType: 'text' });
    ovservable1.subscribe({
      next: (response) => {
        console.log('取得したlargeData:', response.length);
      },
      error: (err) => {
        console.error('largeDataの取得中にエラーが発生しました:', err);
      },
      complete: () => {
        console.log('largeDataの取得が完了しました。');
      }
    });

app.get('/chunked-text', (req, res) => {
  // ヘッダーの設定 (Content-Type は必要、Transfer-Encoding: chunked はExpress/Node.jsが自動で追加)
  res.set('Access-Control-Allow-Origin', '*');
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  let count = 0;
  const intervalId = setInterval(() => {
    count++;
    //const dataChunk = `データチャンク #${count} - ${new Date().toLocaleTimeString()}\n`;
    const dataChunk = "x".repeat(1024 * 1024); // 1MBのデータチャンクを生成
    console.log(`Sending chunk: ${new Date().toLocaleTimeString()}`);

    // データチャンクを書き込む
    res.write(dataChunk);

    if (count >= 5) {
      clearInterval(intervalId);
      // 全てのデータ送信が完了したら res.end() を呼び出す
      res.end('全てのデータ送信が完了しました。\n');
      console.log('Response ended.');
    }
  }, 1000); // 1秒ごとにチャンクを送信
});

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?