Home > Software design >  typescript problem with adding array of objects to new array
typescript problem with adding array of objects to new array

Time:12-24

I'm trying to show my data(recipes) on frontend. When I console.log(data) that I get from server I have object with property of 'msg' that contains array of objects.. I can access that array with data['msg' as keyof typeof data]) So when I console.log that I get an array of objectslogging msg property of data Now my problem is when I try to assign that array to this.recipe array. When I try this.recipe = data['msg' as keyof typeof data] I get an error:

Type 'Function' is missing the following properties from type 'Recipe[]': pop, push, concat, join, and 27 more.

But when I try use push() I get

Type 'Function' is missing the following properties from type 'Recipe': description, ingredients

I'm relatively new to Angular and I'm lost. If you need some other chunks of my code let me now, I didn't want to copy paste lot of it, because I'm not sure where problem is and what would be helpful.I've put here the file where I get the problem.

Code where I get problem:

export class ListComponent implements OnInit {
  public recipes: Recipe[];
  constructor(private _recipeService: RecipeService) { }

  ngOnInit(): void {
    this.readRecipes();
  }
  readRecipes() {
    this._recipeService.readRecipes().subscribe({
      next: (data) => {
        this.recipes = data['msg' as keyof typeof data];
      }
      ,
      error: (error) => console.log(error),
      complete: () => console.info('complete')

    }

    )
  }

}

my recipe.service.ts file:

export class RecipeService {
  private baseUri: string = "http://localhost:8080";
  private headers = new HttpHeaders().set('Content-Type', 'application/json')
  constructor(private http: HttpClient) { }


  createRecipe(recipe: Recipe) {
    return this.http.post(this.baseUri   '/create', recipe, { headers: this.headers });
  }

  readRecipes() {
    return this.http.get(this.baseUri   '/read', { headers: this.headers });
  }

  updateRecipe(recipe: Recipe) {
    return this.http.put(this.baseUri   '/update', recipe, { headers: this.headers });
  }

  deleteRecipe(id: string) {
    return this.http.delete(this.baseUri   '/delete/'   id, { headers: this.headers });
  }
}

backend part of code for read route:

router.get('/read', (req, res, next) => {
Recipe.find({}, (err, recipes) => {
    if (err)
        res.status(500).json({
            errmsg: err
        });
    res.status(200).json({
        msg: recipes
    });

});
});

CodePudding user response:

A simpler way to do this is to use the async pipe in Angular:

@Component({
  template: `
    <ul *ngIf="(employees$ | async).length">
      <li *ngFor="let employee of employees$ | async">{{employee.name}}</li>
    </ul>  
  `
})
export class EmployeesComponent implements OnInit { 
  employees$: Observable<Employee[]>;
 
  constructor(private service: MyService) {}
 
  ngOnInit() {
    this.employees$ = this.service.getEmployees$();
  }
}

Here's a fork of your Stackblitz that shows the list of recipes: https://stackblitz.com/edit/angular-ivy-r97jph?file=src/app/components/list/list.component.ts

CodePudding user response:

Just to write here that I found solution. On the backend I send response as res.JSON({msg:recipes}) and I couldn't access to this 'msg' but when I changed this to response JSON with only parenteses res.JSON(recipes) than on frontend with data I get those array and I can assign it with this.recipes=data and it's working now

  • Related