-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

  }
}
1
  • 1
    You can use of(this.products). It's imported from rxjs Commented Nov 1, 2018 at 12:09

4 Answers 4

9

use the of operator

import { of } from 'rxjs';


return of(this.products);
Sign up to request clarification or add additional context in comments.

Comments

3

Use from

import { from } 'rxjs'

export class ProductService {

  products: IProduct[];

  getProducts(): Observable < IProduct[] > {
    this.products = [{...}, {...}];
    return from(this.products);
  }
}

Comments

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";

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.