Angular7-AppComponent中的访问参数 [英] Angular7 - access parameter in Appcomponent

查看:62
本文介绍了Angular7-AppComponent中的访问参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序需要使用品牌代码来确定样式和dom.

My application requires a brand code to determine the style and dom.

当前加载的URL为www.SiteName.com/HBL(HBL = brandName)

currently the on load my URL would be www.SiteName.com/HBL (HBL = brandName)

这是一个简单的网站,其中只有页眉,页脚和搜索组件.

It is a simple site where it has the only header, footer, search component.

但是我需要从服务api获取品牌信息.

but I need to get the Brand info from service api.

因此,在Appcomponent.ts中,我注入了ActivatedRoute,在ngOnInit方法中,我订阅了paramMap.

So in Appcomponent.ts, I injected ActivatedRoute and in the ngOnInit method, I subscribed paramMap.

加载应用程序时,我得到的参数值为空.

When I load the app I am getting null parameter value.

这是我所做的

我的app.compnent.html:

<div class="container">
  <header [brand]="brand"></header>
  <!-- <esw-search></esw-search> -->
  <router-outlet></router-outlet> - Search will be populated thru route 
  <esw-footer></esw-footer>
</div>

本来可以避免使用路由器,但是有时可以直接访问搜索页面.

I could have avoided router but sometimes the search page will be directly accessible.

例如www.SiteName.com/HBL/search?trackingnumber=123456;language=zh_CN

like www.SiteName.com/HBL/search?trackingnumber=123456;language=en

我的路由组件:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { NotFoundComponent } from './notfound/notfound.component';
import { SearchComponent } from './tracking-search/search/search.component';

const routes: Routes = [
  { path: '', component: SearchComponent },
  { path: ':brandName/search', component: SearchComponent },
  { path: ':brandName/', component: SearchComponent },
  { path: '404', component: NotFoundComponent },
  { path: '**', redirectTo: '404' }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

我的appcomponent.ts代码:

@Component({
  selector: 'esw-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'logistics-tracking-ui';
  apiUrl: string;
  brand: Brand;

  constructor(
    private tracking: TrackingService,
    private route: ActivatedRoute) {
  }

  ngOnInit(): void {

    this.route.paramMap.subscribe(params => {
      const brandName = params.get('brandName');
      this.tracking.getBrandData(brandName).subscribe((response) => this.brand = response);
    });
  }
  }
}

SearchComponent.htm:

SearchComponent.htm:

<div class="card-body">

  <div class="card mx-auto">
    <div class="card-body">
      <h3 style=" text-align: center"> Track your International Package</h3>
      <div>
        <span class="ui-float-label">
          <input [(ngModel)]="trackingNumber" id="float-input" type="text" size="30" pInputText>

          <label for="float-input">Tracking Number</label>

        </span>
        <button pButton type="button" label="Click" (click)="searchTracking()"></button>
      </div>
      <esw-search-details [trackingDetails]='trackingDetails$'></esw-search-details>
    </div>
  </div>

</div>

searchComponent.ts:

searchComponent.ts:

@Component({
  selector: 'esw-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
  trackingNumber = '';
  trackingDetails$: Observable<any>;

  constructor(private trackingservice: TrackingService) { }

  ngOnInit() {
  }

  searchTracking(): void {
    alert('Search Clicked' + this.trackingNumber);
    if (!this.trackingNumber.trim()) {
      // if not search term, return empty hero array.
      // Publish error message
      console.log('Invalid Input');
      return;
    }

    this.trackingDetails$ = this.trackingservice.getTrackingDetails(this.trackingNumber, 'en-GB');


  }

注意:我没有为搜索&添加太多逻辑serachDetails组件.

Note: I have not added much logic to search & serachDetails component.

问题在于我

  1. 访问App组件中的品牌参数值.
  2. 在app.coponent.html中定义布局的这种方法正确吗?
  3. 有什么更好的方法可以使用吗?

对不起,这是我的第一个有角度的项目,我们将为您提供任何帮助.

Sorry this is my first angular project, any help will be appriciated.

推荐答案

如果您要通过传递进出口的路线,则必须注意JS的异步加载.假设您的api调用,导出和导入设置正确,Api调用完成,并且在加载标头组件之后填充品牌((在api调用完成后,通过在应用程序组件中添加控制台日志进行验证.加载标头后将看到它的日志,这使得标头组件的ngOnInit方法无法访问它).因此,您可以阻止加载,直到拥有必需的元素为止:

If you want to go the route you are with passing the the exports/imports, then you have to be careful of the asynchronous loading of JS. Assuming your api call, exports, and imports are set up correctly, the Api call is completed and the brand is filled after the header component is loaded, (verify by adding console log in the app component after the api call is completed. You'll see it logs after the header loads, making it inaccessible to the header component's ngOnInit method). So you can either prevent loading until you have the required element:

<header *ngIf="ReturnedObject.brand" [brand]="brand"></header>

或者您也可以在页面加载了Ng生命周期挂钩之后加载元素,例如

Or you can load the element after the page is loaded with Ng life cycle hooks, such as

ngAfterContentInit(){}

(这不是一个很好的选择,因为您的页面将以任何默认品牌加载,然后在品牌更新后重新加载)

(this is not a great option as your page will load with whatever default branding, then it will reload once the brand is updated)

我的首选方法

您可以根据需要使用"{{}}"表示法来动态命名元素的类,而不是通过传递导出来加载其他组件的方法,而应在父组件中设置该类,然后加载子组件:

You can use the "{{}}" notation to dynamically name your class of an element as needed, and instead of passing an export to load another component, set the class in the parent component, then load the child component:

(在您的孩子的CSS中)

(in your child css)

.texas {
background-image: texasFlag.png;
}
 .newYork {
background-image: newYorkFlag.png;
}

(在您的父HTML中)

(in your parent html)

<header class="{{ReturnedObject.brand}}"></header>
<your-child-component></your-child-component>
<footer class="{{ReturnedObject.brand}}"></footer>

这样,父级已经在孩子开始加载之前设置了该类,从而消除了父级和子级组件正在加载的竞赛".

That way, the class is already set by the parent before the child starts to load, taking away the "racing" your parent and child component are doing to load.

这篇关于Angular7-AppComponent中的访问参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆