如何从角度5

时间:2018-07-31 07:55:08

标签: angular typescript

我有一个仪表板组件,该组件对于所有页面都保持不变,而负载组件是其他组件之一,该组件根据路由器出口而变化。如果要删除管理负载组件中的所有负载,我想在仪表板组件中隐藏“管理负载”按钮。谷歌搜索后,我仍然坚持下去。任何帮助将不胜感激。 这是我的仪表板组件HTML文件

<div class="container-fluid">
        <div class="row">
            <div class="col-lg-3 side-nav">
                <div class="panel">
                    <div class="welcome">
                        <img src="assets/img/welcome.png" class="img-responsive" alt="">
                    </div>
                    <nav class="navbar navbar-default">
                        <div class="container-fluid">
                            <!-- Brand and toggle get grouped for better mobile display -->
                            <div class="navbar-header">
                                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#side-navbar" aria-expanded="false">
                                    <span class="sr-only">Toggle navigation</span>
                                    <span class="icon-bar"></span>
                                    <span class="icon-bar"></span>
                                    <span class="icon-bar"></span>
                                </button>
                            </div>
                            <!-- Collect the nav links, forms, and other content for toggling -->
                            <div class="collapse navbar-collapse" id="side-navbar">
                                <ul class="nav nav-pills nav-stacked btn-collpase panel_show collapse in">
                                    <li routerLinkActive="active">
                                        <a href=""  routerLink="/dashboard">Dashboard</a>
                                    </li>
                                    <li routerLinkActive="active">
                                        <a href="" routerLink="/dashboard/postLoad">Post Load</a>
                                    </li>
                                    <li *ngIf="this.loads.length > 0">
                                        <a href="" routerLink="/dashboard/manageLoad">Manage Loads</a>
                                    </li>
                                </ul>
                            </div>
                            <!-- /.navbar-collapse -->
                        </div>
                        <!-- /.container-fluid -->
                    </nav>
                </div>
            </div>
            <div class="col-lg-9">
                <router-outlet></router-outlet>
            </div>
        </div>
        <hr>
        <!-- why-us-setion end -->
        <div class="clearfix"></div>
    </div>

这是仪表板组件ts文件

import { Component, OnInit } from '@angular/core';
    import {TruckService} from "../services/truck.service";
    import {LoadService} from "../services/load.service";
    import {Observable} from "rxjs/Observable";

    @Component({
        selector: 'app-dashboard',
        templateUrl: './dashboard.component.html',
        styleUrls: ['./dashboard.component.css']
    })
    export class DashboardComponent implements OnInit {
        loads  = [];
        constructor(private loadService:LoadService) { }

        ngOnInit() {
            this.loadService.getLoads().subscribe(data=>{
                this.loads = data;
                console.log("load data is "+data);
            });
        }

    }

这是管理加载HTML文件

<div *ngIf="loads.length > 0">
<h3>Your Loads</h3>
<table class="table-responsive table-stripped table-bordered tab" width="90%;">
    <thead style="text-align: center;">
    <tr style="padding: 5px;">
        <td>From</td>
        <td>To</td>
        <td>Weight</td>
        <td>Date</td>
        <td>Action</td>
    </tr>
    </thead>
    <tr style="height: 40px;text-align: center;vertical-align: middle;" *ngFor="let load of loads">
        <td style="">{{load.from_name}}</td>
        <td>{{load.to_name}}</td>
        <td>{{getLoadWeight(load.truck_capacity_id)}}</td>
        <td>{{ toDate(load.posted_at)}}</td>
        <td><button class="btn btn-primary" routerLink="/dashboard/viewTrucks/{{load.id}}">View Trucks</button>
            <button class="btn btn-danger" (click)="deleteLoad(load.id)">Delete Load</button>
        </td>
    </tr>
</table>

这是设法加载component.ts文件

import { Component, OnInit } from '@angular/core';
    import {LoadService} from "../../services/load.service";
    import {TruckService} from "../../services/truck.service";
    import {AlertService} from "../../services/alert.service";
    import {NavigationExtras, Router} from "@angular/router";

    @Component({
      selector: 'app-manage-load',
      templateUrl: './manage-load.component.html',
      styleUrls: ['./manage-load.component.css']
    })
    export class ManageLoadComponent implements OnInit {
        loads  = [];
        loadWeights = [];
       //  myload;

        constructor(private loadService:LoadService,private truckService:TruckService,private alertService:AlertService,private router:Router) { }

      ngOnInit() {
        this.loadService.getLoads().subscribe(data=>{
          this.loads = data;
          console.log("load data is "+data);
          });
        this.truckService.getTruckCapacity().subscribe(data=>{
            console.log("load weights are "+JSON.stringify(data));
            this.loadWeights = data;
        });
      }

      getLoadWeight(id){
         let weight:String = "";
           this.loadWeights.map(function(item) {
              if(item.id == id){
                  console.log("this weight is "+item.name);
                  weight =  item.name;
              }
          });
          return weight;
      }

      toDate(date){
          let hdate = new Date(date);
          let mytime = hdate.getDate() + '/' + (hdate.getMonth()+1) + '/' + hdate.getFullYear();
          return mytime;
      }
        deleteLoad(id){
          this.loadService.deleteLoad(id).subscribe(data=>{
              if(data['status'] == "success"){
                  this.loadService.getLoads().subscribe(data=> {
                      this.loads = data;
                  });
                this.alertService.alertSuccess(data['message'],'');
              }else if(data['status'] == "error"){
                  this.alertService.alertError(data['message'],'');
              }
          });
        }


    }

如果您需要在这里加载服务文件

import { Injectable } from '@angular/core';
    import {HttpClient, HttpErrorResponse} from "@angular/common/http";
    import { Observable } from "rxjs/Observable";
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';

    @Injectable()
    export class LoadService {

        constructor(private http:HttpClient) {
        }

        getLoads(){
            return this.http.get("http://localhost:3002/load/get-loads")
                .catch(this.getLoadsErrorHandler)
        }
        getLoadsErrorHandler(error:HttpErrorResponse) {
            return Observable.throw(error.message || "Server Error");
        }

        deleteLoad(id){
            return this.http.delete("http://localhost:3002/load/delete-load?id="+id)
                .catch(this.deleteLoadErrorHandler)
        }
        deleteLoadErrorHandler(error:HttpErrorResponse) {
            return Observable.throw(error.message || "Server Error");
        }
        getCurrentLoad(id){
            return this.http.get("http://localhost:3002/load/get-current-load?id="+id).map(response => response)
                .catch(this.getCurrentLoadErrorHandler)
        }
        getCurrentLoadErrorHandler(error:HttpErrorResponse) {
            return Observable.throw(error.message || "Server Error");
        }

    }

任何帮助都会受到高度重视。

1 个答案:

答案 0 :(得分:0)

我了解您的问题。而且我可以清楚地看到您正在通过点击服务从数据库中获取仪表板组件中的负载。由于尚未加载其他组件,因此无法更新另一个组件中的一个组件数据。 因此,您可以执行以下操作:每5秒点击一次获取加载服务。 因此,当您从管理负载组件进行更新时,当您进入仪表板组件时,它将获取新数据,并且每隔5秒就会从数据库中获取更新的数据。

您可以使用匿名订阅来访问API。在此过程中,您将导入AnomymousSubscription,创建其对象,然后创建一个set计时器并函数a,它将连续命中。

希望它能对您有所帮助。