-1

How can you convert an array to an observable array in angular 6. I am trying to return an observable while having an array. I'm doing this so that instead of an HTTP request I can return hard-coded data.

I have the following interface:

export interface IProduct {
  productId: number;
  productName: string;
  productCode: string;
  releaseDate: string;
  description: string;
  price: number;
  starRating: number;
  imageUrl: string;
}

Then I have this service:

export class ProductService {

  products: IProduct[];

  getProducts(): Observable<IProduct[]> {
    this.products = [
      {
        'productId': 2,
        'productName': 'Black cat',
        'productCode': 'GDN-001',
        'releaseDate': 'March 18, 2018',
        'description': 'Can punch peoples faces.',
        'price': 32.00,
        'starRating': 5,
        'imageUrl': 'https://placekitten.com/400/420'
      },
      {
        'productId': 3,
        'productName': 'T Cat',
        'productCode': 'GDN-002',
        'releaseDate': 'March 18, 2018',
        'description': 'Can shoot guns.',
        'price': 32.00,
        'starRating': 2.2,
        'imageUrl': 'https://placekitten.com/400/420'
      }
    ];

    //paste here how to return the array to observable

  }
}
Mo D Genesis
  • 5,187
  • 1
  • 21
  • 32

4 Answers4

8

use the of operator

import { of } from 'rxjs';


return of(this.products);
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
3

Use from

import { from } 'rxjs'

export class ProductService {

  products: IProduct[];

  getProducts(): Observable < IProduct[] > {
    this.products = [{...}, {...}];
    return from(this.products);
  }
}
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
2

If you're using Rxjs 5 or earlier:

You can just use

return Observable.of(this.products);

make sure to import,

import { Observable } from "rxjs";
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

You can use of which will return Observable of argument that of has gotten. Import it from import { of } from 'rxjs';

return of(this.products);
Artyom Amiryan
  • 2,846
  • 1
  • 10
  • 22