angular始めました。
動かすために調べたことをメモしています。
566 views
パラメーター付きでgetしている個所は、ngOnInit関数の中。
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { RouterModule, Router } from '@angular/router';
import { SessionService } from '../session.service';
export class ProjectRecord {
project_id: number = 0;
name: string = "";
}
export class Project {
public Project: ProjectRecord|null = null;
}
export class ProjectsTable {
public error_code: number|null = null;
public message: string|null = "";
public records: Project[] = [];
}
@Component({
selector: 'app-projects',
templateUrl: './projects.component.html',
styleUrls: ['./projects.component.css']
})
export class ProjectsComponent implements OnInit {
test:string="aiueo";
projects:ProjectsTable|null = null;
constructor(private session: SessionService, private client: HttpClient, private router:Router) { }
ngOnInit(): void {
let httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/x-www-form-urlencoded',
})
}
let params = new HttpParams();
let token = this.session.token;
console.log(token);
// params = params.append("token", "53595bfa36a9eb60d28a5e11ff8964c03d1a6b2c");
params = params.append("token", token);
this.client.get<ProjectsTable>("http://localhost/api/v1/projects/search/", {params: params})
.toPromise()
.then((res:ProjectsTable)=>{
this.projects = res;
//console.log(res);
//プロジェクト一覧取得成功
})
.catch((error)=>{
});
}
getしたときのデータ形式は次のような形式。
{
error_code:0,
message:"",
records:[
{Project:{project_id:xxx, name:yyy},
{Project:{project_id:xxx, name:yyy},
{Project:{project_id:xxx, name:yyy},
・・・
]
}
これは、全体をProjectTableクラスで受取る。
recordsは、ProjectTableの中に配列のrecordsで取得する。
records自体はProjectクラスで受取る。
ProjectのレコードはProjectRecordクラスで受け取る。
この間にProjectクラスを挟む必要があることに気づかずハマった。
データ構成が {Project:{project_id:xxx, name:yyy}となっちゃっているのがややこしいけど、別のテーブルも受信したときに分けられるメリットもあるため、こうしていることを忘れていたことが原因。
あと、今はコンポーネントの中でgetしているが、本来はサービスでやるのが正しい。
今回は実験なので、コンポーネントの中に書いている。
Page 23 of 38.
1.angular flex layoutについて.docx
すぺぺぺ
本サイトの作成者。
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
ChatGPTで自動プログラム作成に取り組み中。
https://www.osumoi-stdio.com/novel/