AngularサービスにAPIキーとAPIユーザー名を追加する方法

API キーと API ユーザー名を Angular サービスに追加する方法を教えてください。

例:

return this.http.get('https://converge.trydiscourse.com/categories.json', { 'Api-Key': '123456789', 'Api-Username': 'system' });

ここでエラーが発生しています。

問題の原因はおそらく、コードが Api-KeyApi-UsernameGET リクエストのクエリパラメータとして追加している点にあると考えられます。これらはクエリパラメータではなく、リクエストのヘッダーに含める必要があります。このページの上部にある「Authentication」セクションには、設定方法を示す curl の例があります。https://docs.discourse.org/

自分で問題を解決しました。

fetchCategory() {
  const headers = new HttpHeaders()
    .set('Api-Key', '123456')
    .set('Api-Username', 'abcd');
  const result = this.http.get('https://url.json', { headers });
  return result;
}

また、ブラウザ側で CORS を有効にしたところ、正常に動作するようになりました。