Angular - przekazywanie funkcji

0

Witam, proszę o wyrozumiałość bo dopiero zaczynam przygodę z Angularem.
Mój problem polega na tym że w komponencie new-order.component.ts chciał bym wywołać funkcję getOrders() z **order-list.component.ts **.
Nie wiem czy jest to możliwe ale próbowałem już rożnych sposobów i nic nie dawało oczekiwanego rezultatu. Proszę o pomoc

new-order.component.ts

import { Component, ViewChild } from '@angular/core';
import { MatDialogRef,  } from '@angular/material';
import { OrderFormComponent } from '../order-form/order-form.component';
import { OrderService } from '../order.service';

@Component({
  selector: 'app-new-order',
  templateUrl: './new-order.component.html',
  styleUrls: ['./new-order.component.scss'],
  
})
export class NewOrderComponent  {
  @ViewChild('orderForm') orderForm: OrderFormComponent;
  constructor(
    private dialogRef: MatDialogRef<NewOrderComponent>,
    private orderService: OrderService
   
  ) { }

  createOrder(){
    this.orderService.addData(this.orderForm.form.value)
    .subscribe(this.onCreatingSuccess.bind(this),this.onCreatingFailure.bind(this))
  }

   private onCreatingSuccess(){
    console.log('Sucess');
    this.dialogRef.close();
  }


  ngAfterViewInit() {
    console.log('neworder')
     }

  private onCreatingFailure(){
    console.log('Failure')
  
  }

}

order-list.component.ts

import { Component, OnInit } from '@angular/core';
import { OrderService } from '../order.service';
import { Order } from '../../../model/order';


@Component({
  selector: 'app-order-list',
  templateUrl: './order-list.component.html',
  styleUrls: ['./order-list.component.scss']
  
  
})
export class OrderListComponent implements OnInit {
 
  orders: Order[] ;
  
  constructor(
    private orderService: OrderService) {
    }

getOrders() : void {
  this.orderService.getAll().subscribe((orders) => {
    this.orders = orders;
  });
}


ngAfterViewInit() {
console.log('orderlist')
}
  ngOnInit() {
    this.getOrders()
    
  }

}

0

Jeżeli order-list.component.ts jest dzieckiem new-order.component.ts to możesz wywołać to tak jak kombinujesz aktualnie przez @ViewChild.
Pokaż jeszcze kod html tych komponentów, może źle podczepiasz referencję :)

0

new-order.component.html

<mat-dialog-content>
 <app-order-form #orderForm></app-order-form> 
</mat-dialog-content>

<mat-dialog-actions>
<div class="row">
  <div class="col">
    <button mat-raised-button mat-dialog-close>Cancel</button>
    <button (click)="createOrder()" mat-raised-button color="primary">Create</button>
  </div>
</div>

</mat-dialog-actions>

order-list.component.html

<div id="container">
    <h2>The list</h2>
    <ul>
      <li *ngFor="let item of orders">{{item.zam_nag_id}} |{{item.data_realizacji}} </li>
    </ul>
  </div>

0

A co jeśli tak jak w moim przypadku nie mam relacji pomiędzy tymi komponentami?

0

taki tip: @ViewChild() stosuje się w przypadku gdy chcesz obserwować zmiany w komponencie, który jest "zagnieżdzony" w rodzicu
przykład: masz jakiś input i to co w nim się zadzieje, chcesz mieć od razu widoczne zmiany w labelce w rodzicu

to co potrzebujesz to osobny serwis do obsługi metod, które są współdzielone między komponentami lub możesz przerobić istniejący komponent order-list.component na order-list.service - Twój wybór
zerknij tu i przeanalizuj: https://angular.io/tutorial/toh-pt4
to czego tu brakuje to @Injectable() w order-list.component, ale jak wspomniałem, dobrą praktyką jest trzymać metody współdzielone w osobnym serwisie

EDIT: nie zwróciłem uwagi, że masz już serwis, to chyba wystarczy przenieść metodę do serwisu i powinno śmigać

EDIT2: dobra, dopiero teraz widzę o co chodzi, dla mnie już chyba dość czytania kodu na dziś... :) sorki, nie chciałem wprowadzić w błąd...

0

Nie wiem co robię źle ale próbowałem już na milion sposobów to zrobić i brak rezultatów. Jeżeli ktoś wie o co chodzi proszę dać znać. Przeniosłem funkcje do service ale po wywołaniu funkcji nic się nie ładuje.

order.service.ts

import { Injectable, ChangeDetectionStrategy, ViewChild } from '@angular/core';
import { Observable, throwError, Observer } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import {Order} from '../../model/order'
import { MatPaginator, MatTableDataSource } from '@angular/material';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};
@Injectable({
  providedIn: 'root'
})
export class OrderService {
//@ViewChild(OrderListComponent) orderList: OrderListComponent;
@ViewChild(MatPaginator) paginator: MatPaginator;

baseUrl = 'http://localhost/skplanes/api';
orders: Order[];
dataSource: MatTableDataSource<Order>;
           
constructor(private http: HttpClient,
            ) {this.dataSource = new MatTableDataSource(this.orders) }



  getAll(): Observable<Order[]> {
    return this.http.get(`${this.baseUrl}/list.php`).pipe(
      map((res) => {
        this.orders = res['data'];
        return this.orders;
    }),
    catchError(this.handleError));
  }

  getData(){
    console.log(this.getAll().subscribe(res => this.dataSource.data = res))
    return this.getAll().subscribe(res => this.dataSource.data = res)
    
  }

 
  addData(order: Order): Observable<Order[]> {
    return this.http.post(`${this.baseUrl}/insert.php`,  order )
      .pipe(map((res) => {
        this.orders.push(res['data']);
        return this.orders;
      }),
      catchError(this.handleError));
  }


  private handleError(error: HttpErrorResponse) {
    console.log(error);
    return throwError('Error! something went wrong.');
    
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }
 
}

order-list.component.html

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef> Id. </th>
    <td mat-cell *matCellDef="let element"> {{element.zam_nag_id}} </td>
  </ng-container>
<table>

order-list.component.ts

import { Component, OnInit, ViewChild, Injectable, ViewChildren } from '@angular/core';
import { OrderService } from '../order.service';
import { Order } from '../../../model/order';
import { MatPaginator, MatTableDataSource } from '@angular/material';


@Component({
  selector: 'app-order-list',
  templateUrl: './order-list.component.html',
  styleUrls: ['./order-list.component.scss']
})
@Injectable() 
export class OrderListComponent implements OnInit {
  //@ViewChild(MatPaginator) paginator: MatPaginator
  @ViewChild('orderservice') orderservice: OrderService;

  displayedColumns: string[] = ['id','status','data_realizacji','uwagi'];
  //dataSource: MatTableDataSource<Order>;
  orders: Order[] ;

  constructor(
    private orderService: OrderService) {
      //this.dataSource = new MatTableDataSource(this.orders);
    }


  ngOnInit(){
    this.orderService.getData();
    console.log(this.orderService.getData())
    //return this.orderService.getAll().subscribe(res => this.dataSource.data = res)
  }

  ngAfterViewInit() {
    //this.dataSource.paginator = this.paginator;
  }
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1