Daniel Grindstaff
Daniel Grindstaff

Reputation: 105

Spltting a string returns undefined error

I have returned data of any from an API call. I believe the data is a string delimited by semicolons. I am trying to split the string so I can display the sub strings in the html via string interpolation and then make use of each sub string in sebsequent page. I tried splitting the data in the component code and keep getting back 'split not recognized on undefined'.

I have searched for alternatives like Slice but can't find much of anything.

TS Code:

export class ItemComponent implements OnInit {

  items: any;
  itemsArray: string[];

  constructor(private ailmentService: AilmentService, private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.ailmentService.selectAilment(this.activatedRoute.snapshot.params.problemId).subscribe(data => this.items = data);
    this.itemsArray = (this.items as string).split(';');
  }
}

HTML Code:

<tr *ngFor="let item of itemsArray">
<td>{{item}}</td>

Results are

ERROR TypeError: Cannot read property 'split' of undefined

Upvotes: 0

Views: 183

Answers (1)

Divneet
Divneet

Reputation: 718

export class ItemComponent implements OnInit {

  items: any;
  itemsArray: string[];

  constructor(private ailmentService: AilmentService, private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.ailmentService.selectAilment(this.activatedRoute.snapshot.params.problemId).subscribe(data => {
            this.items = data[0];
            this.itemsArray = (this.items as string).split(';');
        });
  }
}

The problem with your implementation was that you were trying to split the string outside the subscribe method. These are asynchronous calls and your implementation called split before the server returned the data. Also the return type of yor data this.items was array so you need to iterate over this array and get the result. Assuming that you have one long string in your array, the above code should help!!

Upvotes: 1

Related Questions