简体   繁体   English

如何在父组件中为共享组件提供routerLink

[英]How to provide routerLink in Parent component for shared components

I am building this app in angular 6 which uses Rest Country API to fetch all the countries and their details. 我正在用angular 6构建这个应用程序,它使用Rest Country API来获取所有国家及其详细信息。 The problem I am facing is that I am not able to understand how to set routerLink in the parent component in order to fetch the details of the countries. 我面临的问题是我无法理解如何在父组件中设置routerLink来获取国家/地区的详细信息。 Any suggestions would be appriciated. 任何建议都将适用。 Thanks. 谢谢。

UPDATE UPDATE

I am not able to understand how to access the name of the country in order to pass it to the URL. 我无法理解如何将国家/地区名称传递给URL。 I tried almost everything I can think of but nothing seems to work. 我几乎尝试了所有我能想到的,但似乎没有任何效果。

Here are my files: 这是我的文件:

shared.modules.ts shared.modules.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CountryViewComponent } from './country-view/country-view.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    CountryViewComponent
  ],
  exports: [
    CountryViewComponent,
    CommonModule
  ]
})
export class SharedModule { }

Child Component 子组件

country-view.component.ts 国家view.component.ts

import { Component, OnInit, Input, OnDestroy } from '@angular/core';

// importing route related code
import { ActivatedRoute, Router } from '@angular/router';

//importing Service related code
import { CountryViewService } from '../../country-view.service';
import { CountryViewHttpService } from '../../country-view-http.service';

@Component({
  selector: 'app-country-view',
  templateUrl: './country-view.component.html',
  styleUrls: ['./country-view.component.css']
})

export class CountryViewComponent implements OnInit, OnDestroy {

  @Input() currentCountryName: String;

  public currentCountry;

  constructor(private _route: ActivatedRoute, private countryViewHttpService: CountryViewHttpService) {
    console.log("Contry View Constructor  Called");
  }

  ngOnInit() {

    // getting the name of the country from the route
    let myCountryName = this._route.snapshot.paramMap.get('currentCountryName');
    console.log(myCountryName);


    this.countryViewHttpService.getSingleCountryInfo(myCountryName).subscribe(

      data => {
        console.log(data);
        this.currentCountry = data;
      },
      error => {
        console.log("some error occured");
        console.log(error.errorMessage);
      }
    )
  }

  ngOnDestroy() {
    console.log("Country View Component Destroyed");
  }
}

Parent Component HTML 父组件HTML

africa.component.html: africa.component.html:

<!--Home page Html-->
<div class="container-fluid mainContainer">
  <div class="row mainRow">
    <div class="col mainCol">

      <!--Content Section-->
      <div class="row africanCountryRowHeading">
        <div class="backArrow">
          <a [routerLink]="['/home']">
            <i class="material-icons">
              keyboard_backspace
            </i>
          </a>
        </div>
        <div class="col-md-12 upperCol">AFRICA</div>
      </div>

      <a [routerLink]="['/country']">
        <div class="row africanCountryRowContent" *ngIf="allAfricanCountries.length>0">
          <div *ngFor="let africanCountry of allAfricanCountries" class="col-xs-12 col-md-6 col-lg-6 col-xl-6 africanCountriesMainCol">

            <!--Country Iteration div starts here-->
            <div class="row africanCountriesRow">
              <div class="col-md-12 africanCountryCol">
                <div class="panel-flag africanCountriesFlag">
                  <img [src]="africanCountry.flag">
                </div>
                <div class="panel panel-default africanCountriesPanel">
                  <div class="panel-heading africanCountriesPanelHeading">Country: {{africanCountry.name}}</div>
                  <div class="panel-body africanCountriesPanelBody">
                    <p>
                      Capital: {{ africanCountry.capital }}
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <!--Countries Iteration div ends here-->
          </div>
        </div>
      </a>
    </div>
  </div>
</div>

Parent Component Module file 父组件模块文件

africa.module.ts: africa.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
import { CountryViewComponent } from '../shared/country-view/country-view.component';
import { RouterModule, Routes } from '@angular/router';


@NgModule({
  imports: [
    CommonModule,
    SharedModule,
    RouterModule.forChild([
      { path: 'country/:name', component: CountryViewComponent }
    ])
  ],
  declarations: [CountryViewComponent]
})
export class AfricaModule { }

Child Component Service file 子组件服务文件

country-view-http.service.ts: 国家 - 视图 - http.service.ts:

import { Injectable } from '@angular/core';

//importing Http Client to make the request
import { HttpClient, HttpErrorResponse } from '@angular/common/http';


//importing observables related code
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { tap } from 'rxjs/operators';
import { delay } from 'rxjs/operators'


@Injectable({
  providedIn: 'root'
})

export class CountryViewHttpService {

  public currentCountries;
  public baseUrl = 'https://restcountries.eu/rest/v2/name';

  constructor(private _http: HttpClient) { 
    console.log("Country View Service Called");

  }

  // Exception Handler
  private handleError(err: HttpErrorResponse) {
    console.log("Handle error Http calls")
    console.log(err.message);
    return Observable.throw(err.message);
  }


  // method to return single country Informations
  public getSingleCountryInfo(currentCountryName): any {

    let myResponse = this._http.get(this.baseUrl + '/' + currentCountryName + '?fullText=true');
    console.log(myResponse);
    return myResponse;
  } // end get country info function
}

app.component.html app.component.html

<div class="container-fluid mainContainer">
  <!--Navigation Secion-->
  <div class="row navigationMainRow">
    <div class="col-12 navigationMainCol">
      <div class="row navigationLogoRow">
        <div class="col-8 navigationLogoCol">
          <a [routerLink]="['/home']">
            <img src="../assets/images/Terra.png" alt="Logo" id="logo">
          </a>
        </div>

        <div class="col-4 navigationMenuCol">
          <div class="row navigationMenuRow">
            <div class="col-6 navigationLanguageCol">
              <p>
                Language
              </p>
            </div>
            <div class="col-6 navigationCurrencyCol">
              <p>
                Currency
              </p>
            </div>
          </div>  
        </div>
      </div>
    </div>
  </div>
</div>  
<router-outlet></router-outlet>

app.module.ts app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';


// Router Module for Application level Route
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AfricaComponent } from './africa/africa.component';
import { AmericaComponent } from './america/america.component';
import { AsiaComponent } from './asia/asia.component';
import { EuropeComponent } from './europe/europe.component';
import { OceaniaComponent } from './oceania/oceania.component'
import { FilterComponent } from './filter/filter.component';


// import statement for services
import { AfricaService } from './africa.service';
import { AfricaHttpService } from './africa-http.service';

import { AmericaService } from './america.service';
import { AmericaHttpService } from './america-http.service';

import { AsiaService } from './asia.service';
import { AsiaHttpService } from './asia-http.service';

import { EuropeService } from './europe.service';
import { EuropeHttpService } from './europe-http.service';

import { OceaniaService } from './oceania.service';
import { OceaniaHttpService } from './oceania-http.service';


@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AfricaComponent,
    AmericaComponent,
    AsiaComponent,
    EuropeComponent,
    OceaniaComponent,
    FilterComponent,
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot([
      { path: 'home', component: HomeComponent },
      { path: '', redirectTo: 'main', pathMatch: 'full' },
      { path: 'africa', component: AfricaComponent },
      { path: 'america', component: AmericaComponent },
      { path: 'asia', component: AsiaComponent },
      { path: 'europe', component: EuropeComponent },
      { path: 'oceania', component: OceaniaComponent }
    ]),
    HttpClientModule
  ],
  providers: [AfricaService, AfricaHttpService, AmericaService, AmericaHttpService,
    AsiaService, AsiaHttpService, EuropeService, EuropeHttpService,
    OceaniaService, OceaniaHttpService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Assuming that AfricaComponent is what you're referring to as the parent component, use the router link like: 假设AfricaComponent是您所指的父组件,则使用如下的路由器链接:

<a [routerLink]="['/country', africanCountry]">{{africanCountry}}</a>

inside the *ngFor syntax. *ngFor语法中。

You've already implemented routing in AfricaModule . 您已经在AfricaModule实现了路由。 Now you should be able to get the name of the africanCountry from a router params like this inside your CountryViewComponent : 现在,你应该能够从路由器PARAMS你这样的内部得到africanCountry的名称CountryViewComponent

let selectedCountryName;
this._route.params.subscribe((params) => {
  selectedCountryName = params['name'];
});

BTW, are you implementing AfricaModule as a Lazy Loaded module? 顺便说一句,您是否将AfricaModule实现为延迟加载模块? If no, then call the forRoot method instead of the forChild method on RouterModule . 如果没有,则调用forRoot方法而不是forChild的方法RouterModule

EDIT: You're not able to access the country name because you're trying to access the wrong state param name. 编辑:您无法访问国家/地区名称,因为您正在尝试访问错误的州参数名称。 You've defined the country name as name in your routes config. 您已经在路线配置中将国家/地区名称定义为name But you're trying to access it as a snapshot value of currentCountryName key which would not exist. 但是您尝试将其作为currentCountryName键的快照值(不存在)进行访问。 Also using the snapshot to get state or query params isn't really a good practice as these might change asynchronously. 另外,使用快照获取状态或查询参数并不是一个好习惯,因为它们可能会异步更改。

Have a look at this StackBlitz Project 看看这个StackBlitz项目

This should definitely help 这肯定会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 父组件和其他父子组件之间的Angular 5 routerLink - Angular 5 routerLink between parent component and other parent - child component 如何在角度2中为动态加载的子组件提供父模型? - How to provide a parent's model to a dynamically loaded child component in angular 2? 如何将 Storybook 与使用 [routerLink] (Angular) 的组件一起使用? - How to use Storybook with a component using [routerLink] (Angular)? 如何在Vue中使用受控组件在父组件对象中设置值 - How to use controlled components in Vue to set values in parent component object 如何在Vue.js的父组件之外呈现递归组件? - How to render recursive components outside of parent component in Vue.js? 如何在父组件中使用子组件http响应? 角度的 - how to use child components http response in parent component? Angular React:如何动态地将不同类型的子组件附加到父组件中? - React: How to dynamically append child components of differing types into a parent component? 如何让父组件在React中管理子组件的状态? - How to let a parent component manage the state of child components in React? 如何在其中包含所有组件逻辑并将其导出到父组件 - How to have all component logic inside of it and export it to parent components 如何从同一个父组件打开多个组件的模式 - How to open modal for multiple components from same parent component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM