0

I am using a library that handles music tracks, and the track array has a type called "track" which has a title and a link to the relevant track. like this:

Playlist: Track[] = [
  {
    title: 'Audio One Title',
    link: 'Link to Audio One URL'
  },
  {
    title: 'Audio Two Title',
    link: 'Link to Audio Two URL'
  },
  {
    title: 'Audio Three Title',
    link: 'Link to Audio Three URL'
  },
];

I am trying to load it recursively, so I have initialized it:

  msaapPlaylist: Track[] = [];

and I'm trying to push into it from another array like:

  this.msaapPlaylist.push([song.title, song.link]);

it says that I can't push type: any into Track because it lacks properties from type Track: 'title' and 'link' which makes sense! but I don't know how to go any further. Any instruction would be appreciable.

Edit in response to comment, here is what I'm doing. There's a mapquest api function that builds a playlist based on trip length.

import { Component, OnInit } from '@angular/core';

import { Observable, Subject, combineLatest} from 'rxjs';

import { debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
import {MapQuestService} from '../services/mapQuest.service';
import { HttpClient} from '@angular/common/http';
import * as _ from 'lodash';
import { Track } from 'ngx-audio-player';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';



class ToAndFromVals {
  constructor(public readonly from: string, public readonly to: string) {}
}


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  faCoffee = faCoffee;
  title = 'hw5-part1';
  distResult: any;
  timeResult: any;
  maneuvs: any;
  to: any;
  from: any;
  musicData: any[];
  travelTime: any;
  playList: any[] = [];
  playListLength: number;
  msaapDisplayTitle = true;
  msaapDisplayPlayList = true;
  msaapPageSizeOptions = [2, 4, 6];
  msaapDisplayVolumeControls = true;
  // Material Style Advance Audio Player Playlist
  msaapPlaylist: Track[] = [ ];




  private searchTerms: Subject<ToAndFromVals>;


  constructor(private mapQuestService: MapQuestService, private http: HttpClient) {  }

  parseMusic(data: any) {
    const timeRegex = /^(\d+):(\d+)$/;
    for (let song of data) {
      let matchsong = song.length.match(timeRegex);
      let secondsTotal = (parseInt(matchsong[1], 10) * 60) + parseInt(matchsong[2], 10);
      song.totalSeconds = secondsTotal;
    }
    this.musicData = data;
  }


  search(from: string, to: string): void {
    if ( from && to ) {
    let searchy = new ToAndFromVals(from, to);
    this.searchTerms.next(searchy); }}

  ngOnInit() {

    this.searchTerms = new Subject<ToAndFromVals>();
    this.searchTerms.pipe(
        debounceTime(1000),
        distinctUntilChanged(),
        switchMap((x) => {
          return this.mapQuestService.getMap(x.from, x.to);

        }))
      .subscribe((result: any) => {
        console.log(result);
        this.distResult = result.route.distance;
        this.timeResult = result.route.formattedTime;
        this.maneuvs = result.route.legs[0].maneuvers;
        this.travelTime = result.route.time;
        this.createPlaylist();
      });


    // http request to fetch song data and store it

    let url: string = "assets/musicData.json";
    this.http.get(url).subscribe(
      (data: any) => {
      this.parseMusic(data);
      });

    }
    // shuffles list so user doesnt hear same songs over and over
    createPlaylist() {
      this.playList.length = 0;
      this.playListLength = 0;
      let shuffledlist = _.shuffle(this.musicData);
      for (let song of shuffledlist) {
        let left = this.travelTime - this.playListLength;
        if (song.totalSeconds <= left) {
          this.playList.push(song);
          // this.msaapPlaylist.push({title: 'stoofleberg', link: 'assets/music/Ghost Story.mp3', index: 1});
          this.msaapPlaylist.push({title: song.title, link: song.link});
          this.playListLength += song.totalSeconds;
        }
      }
      console.log(this.playList, 'and', this.travelTime, 'and', this.playListLength);
      console.log(this.msaapPlaylist);
    }



    formatTime(seconds){
      if (seconds ===undefined || seconds === null){
        return '';
      }

      let minute = Math.floor(seconds / 60);
      let secondsThing = seconds % 60;
      let hour = Math.floor(minute / 60);
      minute = minute % 60;
      // tslint:disable-next-line: max-line-length
      let wholeThing = hour.toString().padStart(2, '0') + ':' + minute.toString().padStart(2, '0') + ':' + secondsThing.toString().padStart(2, '0');
      return wholeThing;
    }

ngAfterViewInit() {
    this.search('boston', 'poughkeepsie');
  }
}

HTML

 <div class="container">
  <h3>HW5-p1</h3>

  <form >
         <input
         #from
         id="from"
         (keyup)="search(from.value, to.value)" placeholder="From" value="boston"/>

          <input
          #to
          id="to"
          (keyup)="search(from.value, to.value)" placeholder="To" value="poughkeepsie"/>
  </form>

  <hr/>
  <h2>Songs and Lengths</h2>
  <h3>Travel Length {{formatTime(travelTime)}}</h3>
  <h3>Playlist Length {{formatTime(playListLength)}}</h3>
  <ul id="playMusic" *ngFor='let song of playList'>
    <li><a href='assets/music/{{song.title}}.mp3' target='_blank'>{{song.title}}</a> {{song.length}}</li>
  </ul>
</div>



  <hr/>
  <table class="table table-striped" id='maps'>

      <tr><th colspan="4"> Distance: {{distResult}} miles  -  Time: {{timeResult}} </th></tr>
      <tbody *ngFor="let m of maneuvs">
        <tr>
          <td><a href='{{m.iconUrl}}' target=_x>
            <img src="{{m.iconUrl}}"/>
          </a></td>
          <td>{{m.index + 1}}. </td>
          <td>
              <a  href='{{m.mapUrl}}' target=_x>
                  {{m.narrative}} </a>
          </td>
          <td>{{m.distance}}</td>

        </tr>
      </tbody>

    </table>

<div class="container" id="BobDiv">
  <mat-advanced-audio-player [playlist]="msaapPlaylist" [displayTitle]="msaapDisplayTitle"
  [displayPlaylist]="msaapDisplayPlayList" [pageSizeOptions]="msaapPageSizeOptions"
      [displayVolumeControls]="msaapDisplayVolumeControls" [expanded]="true"></mat-advanced-audio-player>
</div>


<router-outlet></router-outlet>

1 Answer 1

1

You're attempting to push an array of strings, not an object, assuming the type of Track is

interface Track {
   title: string;
   link: string
}

Try:

this.msaapPlaylist.push(
  { title: song.title, link: song.link }
);
Sign up to request clarification or add additional context in comments.

2 Comments

now it says cannot read property "title" of undefined. If I take out my html and doublecheck the array, it looks good. If I put it back in, it breaks. however, if I hardcode the value of msaapPlaylist in the class definition instead of loading it with push, it works fine.
Hard to say what the issue is without what youre doing and the stack

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.