0

I'm using ionic as a front end and Laravel as a back end. This is the returned JSON data from an API URL, I want to access just the first element which is a.jpg without anything else, I tried using filenames.[0] but it's just displaying [ which means that it's calling the first character not the first element of the array.

Here's the JSON data:

[{"filenames":"[\"a.jpg\",\"b.jpg\",\"c.jpg\"]"}]

Here's my .ts file

    import { ApiLandingRecipesService} from '../api-landing-recipes.service'

@Component({
  selector: 'app-landing-page',
  templateUrl: './landing-page.page.html',
  styleUrls: ['./landing-page.page.scss'],
})
export class LandingPagePage implements OnInit {
  datauser: any[];
  constructor( public api: ApiLandingRecipesService) { }

  ngOnInit() {
    this.getDataUser();
  }
  async getDataUser() {
    await this.api.getDataUser()
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }

and Here's my service file:

   import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';


const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

const apiUrl = "https://example.com/showimages";
@Injectable({
  providedIn: 'root'
})
export class ApiLandingRecipesService {

  constructor(private http: HttpClient) { }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError('Something bad happened; please try again later.');
  }

  private extractData(res: Response) {
    let body = res;
    return body || [] ; }

  getDataUser(): Observable<any> {
    return this.http.get(apiUrl, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError));
  }


}

2 Answers 2

1

It's because filenames is indeed a string (a json string representation of the array) and not an array.

Try converting the string into an array first.

JSON.parse(filenames)[0]
Sign up to request clarification or add additional context in comments.

6 Comments

Where in the code i should put this? in my .html file i'm accessing filenames like this: <img src="example.com/showimages{{data.filenames[0]}}">
can you provide some more code? where does datacome from?
I provided my .ts and my service code above. It's coming from an apiUrl which is "example.com/showimages" as raw data (JSON) I've connected my ionic app with laravel using api & http
Unfortunately Im not familiar with ionic so I cant exactly tell you what to do. But my guess would be to process the data that is coming from example.com/showimages with Javascript and look for the filenames variable and convert it using the statement above
Is the JSON data you provided coming from this statement? console.log(this.datauser);
|
1

The value of filenames here is a string and not an array, which is why you're getting [ when you try to access the first element.

You probably need to parse the value, here's an example (assuming datauser) is the JSON data you've shown us.

let filename = JSON.parse(datauser[0].filenames)[0]

8 Comments

Thank you & how I can convert it to an array? i read that I should parse the JSON data, but it's already parsed..isn't it?
I've added a solution, assuming that datauser is the json data.
where should I place this line " let filename = JSON.parse(datauser[0].filenames)[0] " ? in the .ts file under " console.log(this.datauser); " ?
Yes, this line should be added after you have fetched and assigned the value to datauser. The filename variable here is the first element of the array, which you were trying to access.
Ok i placed it, and my .html file how can i call it? like this <img src="example.com/showimages{{data.filename}}"> ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.