简体   繁体   中英

get data with observables, subsscribe and http, angular

im trying to get data from an API, ive come so far that i can get the data in controle.log and print it out with json. But, i cant get id, name,... from interface or class. I dont know why i cant get it. someone have a clue?

i have also tried movie[] class instead of IData[] but it doesnt make any diffrens.

export class MoviesService {

private showMovies = new Subject<IData[]>();
movies$ = this.showMovies.asObservable();

  constructor(private http: HttpClient) { }

  getServerData(){
    this.http.get<IData[]>("https://medieinstitutet-wie-products.azurewebsites.net/api/products").subscribe((dataFromApi: IData[]) =>
    this.showMovies.next(dataFromApi))
  }
}



export class ShowmoviesComponent implements OnInit {

 showMovies: IData [] = []
  constructor(private service: MoviesService) { }

  ngOnInit(): any {
    this.service.movies$.subscribe((dataFromService: IData[]) => {
      return this.showMovies = dataFromService,
      console.log(dataFromService)
    })
      this.service.getServerData()   
  }
}


export class Movies{
    id: string
    name: string
    description: string
    price: string
    imageUrl: string
    year: string
    added: string
    productCategory: string

    constructor(
        id: string, 
        name: string, 
        description: string, 
        price: string,
        imageUrl: string,
        year: string,
        added: string,
        productCategory: string){
        this.id = id
        this.name = name
        this.description = description
        this.price = price
        this.imageUrl = imageUrl
        this.year = year
        this.added = added
        this.productCategory = productCategory
    }
}


export interface IData{
 
        id: string
        name: string
        description: string
        price: string
        imageUrl: string
        year: string
        added: string
        productCategory: string
}

<div *ngFor="let m of showMovies">
    {{ showMovies | json}}
</div>

Try to replace your subject by a BehaviorSubject

Also, you are using the ngFor in the wrong way. It should be:

<div *ngFor="let m of showMovies">
    {{ m | json}}
</div>

To finish, don't forget to unsubscribe your observables: In your case you can use take(1) as you need the first ->

 this.http.get<IData[]>("https://medieinstitutet-wie-products.azurewebsites.net/api/products").pipe(take(1).subscribe((dataFromApi: IData[]) =>
    this.showMovies.next(dataFromApi))
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM