1
\$\begingroup\$

I did not have experience with organization project and http-client. I suppose this is the right way. I have data-storage service where I store my data from server. This is data-storage:

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class DataStorageServiceService {

  // URL to web api

  private cateogryUrl = 'api/cateogry';  // URL to web api

  constructor(private http: HttpClient) {  }

  /** GET heroes from the server */
  getCategory(): Observable<CategoryModel[]> {
    return this.http.get<CategoryModel[]>(this.cateogryUrl).pipe(
       map(products => {
          return Object.values(products)

        }),
      catchError(this.handleError('getProduct', []))
    )
  }
}

I have another service ProductsService where I call the getCategory() from method getCagegoryFromServer() and store the data in my list categoryModule.

This is service ProductsService:

@Injectable()
export class ProductsService  {
  cateogoryChanged = new Subject<CategoryModel[]>();

  private categoryModule: CategoryModel[] = [];

  constructor(private shopService: ShopCartService, private dataStorageServiceServiceta: DataStorageServiceService) { }


  getCagegoryFromServer() {
    this.dataStorageServiceServiceta.getCategory().subscribe((category :CategoryModel[]) => {

      this.categoryModule = category;
    })
  }

  getCategory() {
    return this.categoryModule.slice();
  }
}

And finally in my component ProductsComponent I call the method getCagegoryFromServer() and store the data in my list.

This is my ProductsComponent:

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit  {

  constructor(private productsService: ProductsService) {

   }

  ngOnInit() {
    this.productsService.getCagegoryFromServer();

  }

}

Does anyone know a better approach?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.