我目前被困在我的專案中,我需要你的寶貴幫助。
我創建了一個后端,我看到了:

您可能已經注意到,tags鍵應該是一個字串陣列(String[]),但由于我使用 mysql,所以不可能將其存盤在陣列中。
我在 NodeJS 中的后端顯示如下:
router.get('/', (req, res) => {
pool.getConnection((err, connection) => {
if(err) throw err
connection.query('SELECT * from sites', (err, rows) => {
connection.release() // retourne la connection
!err ? res.send(rows) : console.log(err)
})
})
})
這是我的 Angular 應用程式,它應該檢索ISite型別的物件
型別 I 站點:
id: number;
nom: string;
description : string;
imageUrl: string;
rating: number;
tags: string[];
這是我的角度應用程式的服務:
public getSites(): Observable<ISite[]> {
return this.http.get<ISite[]>(this.HOTEL_API_URL).pipe(
catchError(this.handleError)
);
}
顯然我有一個錯誤,因為我嘗試將一個字串放入一個字串陣列(String [])中。
我設法將我的字串轉換為我的一個函式的陣列,因為它只回傳一個物件,但我無法使用 map 函式為幾個物件做到這一點......
public getSiteById(id: number): Observable<ISite> {
return this.http.get<ISite>(this.HOTEL_API_URL id).pipe(
map(response => (
{ ...response, tags: response.tags ? (response.tags as unknown as string).split(',') : []}
),
),
catchError(this.handleError)
);
}
你能幫我嗎謝謝
uj5u.com熱心網友回復:
但不可能將它存盤在陣列中,因為我使用 mysql。
A)在后面,您可以將該欄位“字串化”以存盤在您的資料庫中,并在每次之前將其決議為字串以服務前面的請求。
B)或者,您可以將整個“轉換”放在前面:欄位“標簽”始終是前面介面/類和后面模型/物體中的字串,并且您要在每次你要創建或者你要請求它時都在前面,然后將回應回傳給你:
-
- 當您擁有陣列時,將其字串化(使用JSON.stringify)并將字串化值傳遞給字串欄位:
Type ISite :
}
id: number;
nom: string;
description : string;
imageUrl: string;
rating: number;
tags: string;
}
const tempArrayToString:string = JSON.stringify( this.yourForm.value.tags );
cont obj:ISite = {...this.yourForm.value, tags: tempArrayToString};
您的表單 (this.yourForm) 是唯一仍將欄位視為字串 [] 的表單。在后面,你會在標簽中得到一個字串,你也會回傳一個字串。
注意:如果您需要后面(或前面)的標簽值,您總是可以 getit 決議它。
-
- 當您呼叫該 API 請求該物件時,也將其決議為前端的陣列(使用JSON.parse(string) ):
public getSites(): Observable<ISite[]> {
return this.http.get<ISite[]>(this.HOTEL_API_URL)
.pipe(
map (_arrayObject => _arrayObject.map(_obj => _obj.tags = JSON.parse(_obj.tags))),
catchError(this.handleError)
);
}
uj5u.com熱心網友回復:
Anthony,一般來說,當您需要存盤一個字串陣列時,您可以將其存盤為一個用逗號(或另一個字符)分隔的字串。所以,如果你有 ["one","two","three"],你存盤為 "one,two,three" (*)
//imagine data is in the way {prop1:2,myarray:["1","2","3"]}
sendData(data:any)
{
const sendData={...data,myarray:data.myarray.join(",")}
httpClient.post("my url",sendData)
}
//And in service you can use some like
getDataId(id:number){
return httpClient.get("my url/" id).pipe(
map((res:any)=>({...res,myarray:res.myarray.split(",")})
)
}
getAllData()
{
return httpClient.get("my url").pipe(
map((res:any[])=>{
res.forEach((x:any)=>{
x.myarray=x.myarray.split(",")
})
return res;
}
)
}
因此,您向服務發送一個陣列,然后從服務中獲得一個陣列
(*) 真的是“奇怪的”存盤為“[one,two,three]”(帶有[ ])。如果你不能避免總是可以使用'[' data.myarray.join(",") ']'和x.myarray.replace('[','').replace(']','').split(",")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420173.html
標籤:
下一篇:根據多個變數在SQL中查找匹配值
