Traverse the elements of a BehaviorSubject named Layer_Template

I am currently facing an issue with displaying data from my BehaviorSubject. I have come across a way to iterate through a BehaviorSubject using asyncpipe which subscribes to the Observable

SERVICE

todo.service.ts

@Injectable()
export class TodoService {

todos$: BehaviorSubject<Todo[]> = new BehaviorSubject<Todo[]>( [] ) ;

readonly todoEndPoint = environment.endpoint + "todos"

constructor( private $http: HttpClient) {}

getAllTodos(): Observable<Todo[]>{
return this.$http.get<Todo[]>( this.todoEndPoint )
    .pipe(
      tap( val => this.todos$.next( val ))
    )
}
}

Component where I want to use it

export class TodoListComponent implements OnInit {

constructor( public $todo: TodoService ) {
  $todo.getAllTodos().subscribe()
}

ngOnInit() {
}

}

Template Layer

<div *ngFor="let todo of $todo.todos$ | async">
  {{ todo.text }}
</div>

---------------------------------------------------------- EDIT ------------------------------------------------------------------ I´m getting this Error

ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Is there any possibility to iterate through the data stream of the BehaviorSubject

---------------------------------------------------------- SOLUTION --------------------------------------------------------- My backend sent an Object of Arrays instead of just Arrays. That was the issue, so now I have changed the response to Arrays

Answer №1

While active:

@Injectable()
export class TodoService {

readonly todoEndPoint = environment.endpoint + "todos"

constructor( private $http: HttpClient) {}

getAllTodos(): Observable<Todo[]>{
return this.$http.get<Todo[]>( this.todoEndPoint );
}
}

Within the component:

export class TodoListComponent implements OnInit {

public todoitems$: Observable<Todo[]>;

constructor( private $todo: TodoService ) {
}

ngOnInit() {
     this.todoitems$ = this.$todo.getAllTodos();
}

}

Displayed in Template:

<div *ngFor="let todo of todoitems$ | async">
  {{ todo.text }}
</div>

Answer №2

TS:

service:

retrieveAllTasks(): Observable<Task[]>{
return this.$http.get<Task[]>( this.taskEndpoint );
}

component:

export class TaskListComponent implements OnInit {

//tasks as observable.
public tasks: Observable<Task[]>;

constructor( private $task: TaskService ) {
}

ngOnInit() {
     this.tasks = this.$task.retrieveAllTasks();
}

}

HTML:

<div *ngFor="let task of tasks | async">
  {{ task.description }}
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to insert a button into a specific column of an ngx-datatable within an Angular 8 application?

I am having trouble with this particular HTML code. <ngx-datatable-column name="Option" prop="option" [draggable]="false" [resizeable]="false [width]="250"> <span> <button class="optionButton" type="button" data-to ...

Step-by-step guide for implementing Angular on a production server with the latest universal server rendering feature in angular-cli

I have successfully deployed my Angular application on Azure Server using angular-cli. By running the command ng build --prod --aot and transferring files from the /dist folder to the root website folder, everything is working perfectly! To address SEO c ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

What is the best way to integrate Emotion styled components with TypeScript in a React project?

Currently, I am delving into TypeScript and attempting to convert a small project that utilizes Emotion to TypeScript. I have hit a roadblock at this juncture. The code snippet below export const Title = styled.div(props => ({ fontSize: "20px", ...

Issues encountered while developing a ReactJS application using TypeScript

While attempting to create a React app using the command npx create-react-app client-app --use-npm --typescript, I expected to generate a project with TypeScript files, but instead ended up with index.js and app.js rather than index.tsx and app.tsx. Could ...

Encountering an error when using the Vue 3 TypeScript Composition API for style binding with an asynchronous

I utilized nexttick alongside an async method to update a DOM element. However, I am encountering issues with returning the correct style type. An error message pops up stating: error TS2322: Type 'Promise<{ maxHeight: string; }>' is not ...

Engaging Angular Universal for internal API calls through Express

After researching numerous tutorials and guides on integrating SSR (server-side rendering) into existing angular CLI & Express projects, I successfully configured node with SSR. However, I encountered difficulties in making API calls. My goal is to have a ...

What steps should I take to choose esNext from the typescript menu within visual studio 2017?

When utilizing dynamic import with TypeScript in Visual Studio 2017, I encountered the following error: TS1323(TS) Dynamic imports are only supported when the '--module' flag is set to 'commonjs' or 'esNext'. I attempted to c ...

Choosing between running a single unit test or multiple tests using Karma toggle switch

Currently, I am working on writing unit tests using the Karma/Jasmine combination and I'm curious if there's a way to target a specific spec file for testing instead of running all the spec files in the files array defined in the karma.conf.js fi ...

Angular NodeJS API failing to retrieve search data

I have implemented a search feature using Angular and Node.js. After testing it with Postman, everything seemed to be working fine. However, when I tried connecting it to the front-end Angular application, I encountered an error. Failed to load resource: t ...

Issue encountered while attempting to upload a document in Angular due to Content-Disposition

I am having trouble uploading a file using Angular. Every time I make the request, an error occurs stating: "Request has been blocked by CORS policy: Request header field content-disposition is not allowed by Access-Control-Allow-Headers in preflight respo ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Using currency symbols in Angular 2

I'm currently in Australia and trying to display some currency values. I have the following code: {{ portfolio.currentValue | currency : 'AUD' : true : '4.0' }} However, the result I am getting is A$1,300,000. Is there a way to c ...

Solving Circular Dependencies in React with TypeScript by using smart importing techniques

I've set up a union type in the parent component export type Students = "fresher" | "secondYear" | 'finalYear' | 'postGrad'; A circular dependency is causing issues, and the most obvious solution is to define ...

Variability in Focus Behavior while Opening a URL in a New Tab with window.open()

Here is a code snippet I have been using to open a URL in a new tab: window.open(urlToOpen, '_blank', 'noopener noreferrer'); The issue I am experiencing is that when this code is executed for the first time, it opens the URL in a new ...

Error: The property '...' is not found in the ReactElement<any, any> type, but it is required in the type '{...}'

As a beginner in TypeScript, I am currently working on rendering a page by fetching data from getStaticProps. The code snippet I am using for this purpose is: import React, {FormEvent, useState} from "react"; import { InferGetStaticPropsType } fr ...

Guide to simulate the store.pipe method in an Angular component during unit testing

Just starting out with Angular and I'm trying to write unit tests for a component that retrieves data from the store. I've mocked both the service files and the store itself, but when running the test, I keep encountering the following error. Eve ...

Please exclude any files with the name npm-debug.log.XXXXXX in the .gitignore file

Is there a way to exclude this file from the repository using .gitignore? https://i.stack.imgur.com/mK84P.png I am currently working on Gitlab. I have attempted the following: https://i.stack.imgur.com/2kN21.png Appreciate any help in advance ...

Optimizing performance in React: A guide to utilizing the Context and useCallback API in child

Utilizing the Context API, I am fetching categories from an API to be used across multiple components. Given this requirement, it makes sense to leverage context for managing this data. In one of the child components, the categories can be expanded using ...

What is the best way to set the typing of a parent class to the child constructor?

I am seeking a method to inherit the parameter types of a parent's constructor into the child's constructor. For example: class B extends A { constructor (input) { super(input); } } I attempted the following: class B extends ...