Home > Mobile >  Transform the string of all my objects into an array
Transform the string of all my objects into an array

Time:01-23

I am currently stuck in my project and I need your precious help.

I created a backend, I see this:

As you may have noticed, the tags key should be an array of strings (String[]) but impossible to store it in array because I use mysql.

My backend in NodeJS displays this:

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)

        })
    })
})

And here is my Angular application which is supposed to retrieve an object of type ISite

Type ISite :

  id: number;
  nom: string;
  description : string;
  imageUrl: string;
  rating: number;
  tags: string[];

And here is my service of my angular application :

  public getSites(): Observable<ISite[]> {
    return this.http.get<ISite[]>(this.HOTEL_API_URL).pipe(
      catchError(this.handleError)
    );
  }

Obviously I have an error because I try to put a string in a string array (String[]).

I managed to transform my string into an array for one of my functions because it returns only one object, but I can't manage to do it with the map function for several objects...

  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)
    );
  }

can you help me thank you

CodePudding user response:

but impossible to store it in array because I use mysql.

A) In the back, you can "stringify" that field to store in your DB, and parse it to string everytime before to serve a request made by the front.

B) Or, you can put the whole "transformation" at the front side: Field 'tags' always is going to be a string in the front interface/class and in the back model/entity, and you are to transform it in the front every time you are going to create or you are going to ask for it and back return the response to you:

    1. When you have the array, stringify it (with JSON.stringify) and pass the stringifyed value to the string field:
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};

Your form (this.yourForm) is in the only which still will treat the field as string[]. In the back, you will get an string in tags, and you will retur a string as well.

NOTE: If you would need the tags value in the back (or in the front), you always can getit parsing it.

    1. When you do a call to that API asking for that object, parse it to array (with JSON.parse(string)) in the front side aswell:
  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)
    );
  }

CodePudding user response:

Anthony, in general, when you need store an array of string you can store as a string separate by commas (or by another character). So, if you has ["one","two","three"], you store as "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;
      }
   )
}

So, you send to the service an array and you get from the service an array

(*)really is "strange" store as "[one,two,three]" (with the [ ]). if you can not avoid always can use '[' data.myarray.join(",") ']' and x.myarray.replace('[','').replace(']','').split(",")

  •  Tags:  
  • Related