首页 > 解决方案 > ActivatedRoute 在我的 Angular CLI 中不起作用:11.2.6

问题描述

我正在建立一个显示世界顶级城市列表的网站,当单击任何城市时,将显示该城市的详细信息。

我通过创建 3 个组件开始该项目:home.component.ts(用于列表)、city.component.ts(用于详细信息)和error.components.ts(用于通配符路由)。我还创建了ities.service.ts,在其中对值(id、名称、国家、人口、摘要、详细信息和图像)进行了硬编码。

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

@Injectable({
  providedIn: 'root'
})
export class CitiesService {

  getCities () {
     return [
      { id: 1, name: 'london', country: 'United kingdom', population: 12434823, summary: "As the “capital of capitals” negotiates the uncharted terrain of a post-Brexit world, for now it still reigns atop the planet’s best cities for the fifth year running.", detail: "London is #1 again, for the sixth year in a row. It’s never not topped our World’s Best Cities rankings. But the city is in tough in 2021. There’s been speculation on the impact of Brexit on London’s prosperity ever since the referendum vote was counted in 2016: for 2021, our rankings show the city at #5 for number of Global Fortune 500 companies (identical to 2020), 29th for GDP Per Capita and 52nd for Unemployment. But our new ranking subcategory, the Gini coefficient (which we refer to as Income Equality), shows the city’s alarming disparity between rich and not: London ranks 149th of 263 cities. Could a Brexit deal be an opportunity to redress? Certainly, some of those who voted to leave are hoping, perhaps vainly, that it could be so. Vainly because in September, JPMorgan Chase & Co. was just the latest multinational to abandon the good ship Britain, moving $230 billion from the UK to Frankfurt amidst Brexit uncertainty. But London is still London and the pandemic has made us value other aspects of city life—critical things, like cool, breathable air, which is made possible by a city’s trees and its green, open landscapes. London ranks #16 for the quality of its outdoor experiences, many of which come in the form of spectacular parks that are the legacy of dozens of former country estates that served as hunting grounds for generations of kings and queens. Today, there’s no better urban experience anywhere, no matter the global forces swirling above the ancient streets.", image: "../assets/london.jpg" },
      { id: 2, name: 'newyork', country: 'united states', population: 20320876, summary: "America’s urban heart was broken by the pandemic and has a long way back.", detail: "It’s a grim time to be (almost) on top. As cases spiked in March and April, New York became the U.S.’s nightmarish coronavirus epicenter. Statewide, more than 18,000 COVID-19 patients were in hospitals at one point in April. Daily deaths peaked at 799 in April, and have totaled over 24,000. A few short months ago, all the data made sense. While New York ranks just 64th for the size of its convention center, the Jacob. K. Javits Center was in the process of being renovated to twice its enormity. Most recently, its square footage had been transformed into a 1,200-bed field hospital, with room, if necessary, for 2,900. A year ago, we went on gaily about how New York was reinventing shopping, with the mall of the future at Hudson Yards and Nordstrom and Neiman Marcus vying for supremacy in the chic city. This year, in the #2 shopping city on the planet (behind only Tokyo), there is no breakfast at Tiffany’s. New York, to the surprise of no one, ranks Top 5 in the world for Global 500 companies (#4). And that is part of the enduring allure of the city—the magical thinking that if you hustle hard enough, anyone could be persuaded to meet with you. New York is, above all, a gathering place where brains and bodies in indecent proximity to one another create the sparks of genius, invention, progress. Today New Yorkers stand at the ready, together and alone, on their stoops and balconies ready to defend their city. From vague federal threats of defunding. From shadowy armies to keep calls for justice and reform loom over the city along with an invisible virus. However the world emerges, evolves or pivots out of our collective force majeure, it will happen here first. New York is, after all, #1—or thereabouts.", image: "../assets/newyork.jpg"},
      { id: 3, name: 'paris', country: 'france', population: 12824378, summary: "Just as terrorism subsided, the Notre-Dame inferno struck Parisian resolve anew. But the City of Light builds on resiliently.", detail: "On April 15, 2019, as the Notre-Dame cathedral went up in flames, people in Paris gathered in the streets to pray. Joining them was just about everyone else across the globe with access to a screen. This, of course, was not an isolated catastrophe for the French capital over the past few years. But despite multiple terrorist attacks and the destruction of its iconic cathedral—seemingly insurmountable disaster and hardship—Paris prevails and comes back brighter. Amazingly, despite the tragic fire and a year of the Yellow Vest protests that deterred tourists from visiting the city, Paris matched its 2018 in 2019, with 35.4 million visitors, according to Statista. The City of Light ranks #3 in our Product category, with the second-best Airport Connectivity in the world, a #5 ranking for Museums (the city has more than a hundred) and #7 for Attractions. Leading up to the 2024 Summer Olympics, infrastructure investment has sped up and the city continues to build hotels at a dizzying rate. Two dozen opened in 2019 and the same amount were scheduled to debut in 2020, including the first Bulgari Hotel at 30 Avenue George V. There have been plenty of pandemic-related delays. As the saying goes, Paris is always a good idea. And now that swimming in the waters of the Seine is a thing at Bassin de la Villette public pools, even the locals who notoriously leave town in summer are sticking around. City Hall is promising to build five new outdoor swimming pools in time for the Olympics. So even though Paris is now #26 globally for Parks & Outdoors in 2020, it’s a category ranking that should improve.", image: "../assets/paris.jpg"},
      { id: 4, name: 'moscow', country: 'russia', population: 17125000, summary: "Russia’s beguiling capital is a cultural gold mine spanning the ages.", detail: "Any traveler to Russia will tell you that Russian influence—at least over visitors to the country’s capital—is a very real thing: you’ll fall under the spell of Moscow the minute you set foot in this endlessly fascinating and dynamic destination. Curiosity about Russia has increased as political intrigue has grown, which might explain why Moscow was the 14th-most trending city over the past year, according to our Google Search ranking. The global fascination has as much to do with the spectacular 2018 FIFA World Cup (Moscow’s Luzhniki Stadium in the city’s 360-acre Olympic complex hosted the pivotal final matches) as with the Kremlin’s global ambitions. Accessing all this excitement has never been easier as the curious and opportunistic can fly into Moscow with ease: the city ranks #4 for Airport Connectivity, up one spot over last year. Once you’re on the ground, the recently renovated Moscow subway is increasingly the envy of many Western capitals, as much for its improved efficiency and reach as for its regally art-stuffed stations. Whatever brings you to the city, you’re in for an experience at stark odds with the West’s continuously dismaying news about Russia. Moscow is what Travel + Leisure calls a “revolution of creativity,” giving it an atmosphere of young, free-thinking exuberance that has touched every aspect of city life, from its art and food scenes to quirky, only-in-Russia shared workspaces. The first so-called “post- Soviet generation” of Muscovites has traveled the world, returning with suitcases full of ideas that they’re unpacking to huge effect in their always-proud city, sanctions be damned.", image: "../assets/moscow.jpg" },
      { id: 5, name: 'tokyo', country: 'japan', population: 37435191, summary: "The futuristic metropolis is tapping its ancient feudal roots by investing in street-level livability and resident wellbeing—Olympics or no Olympics.", detail: "Despite earthquakes, tsunamis and typhoons, Tokyo grabbed the #1 spot for Safety. Which is helpful in a place with so much to explore and discover at all hours of the night. Tokyo continues to mesmerize global visitors with its innovation, efficiency and round-the-clock kinetic mobility. It earned the #1 rank in Shopping for its world-class experiences, like Ginza’s luxury department stores, newly enhanced with the art-bedecked and sharply designed Ginza SIX shopping center. Tokyo boasts the second most restaurants of any city worldwide, and ranks #6 in our Culture subcategory (and #3 overall in our Programming category)—even with the postponement of the 2020 Olympics. The show will go on in 2021, pandemic permitting. Here, the famous pulsating Nightlife (#9) can be experienced any way you like, from the glaring lights of Shibuya to the, well, glaring red lights of Kabukicho. For a more low-key bar scene, Zoetrope in Shinjuku offers an awe-inspiring selection of Japan’s famous whisky. With a #2 global rank for Restaurants, Tokyo is moving far beyond its internationally beloved food traditions. The metropolis offers as many restaurants as the rest of our Top 5 cities combined—more than 100,000 in total, so visitors and residents alike could never hope to experience them all. Iconic spots like Den (among the top restaurants in Asia) abound, while busy depachiku (food halls) can be explored below ground all over the city for a much—much—more affordable price. The wave of Japan’s economic revival under Abenomics—the economic policies advocated by departing Prime Minister Shinzō Abe—may have crested thanks to the pandemic, but Tokyo retains the #3 spot for Prosperity globally. That’s driven mainly by a low unemployment rate (ranking #11) and the second-highest number of Global 500 headquarters. Some are household (or at least garage) names: Toyota, Acura, Subaru, Mitsubishi. But SoftBank, while it funds disruptive start-ups around the world, is also changing Japanese business, offering rarely seen perks and benefits to its workers. Japan’s record level of female participation in the workforce is also reflected at the company.", image: "../assets/tokyo.jpg" },
      { id: 6, name: 'dubai', country: 'UAE', population: 6036000, summary: "An alluring blend of over-the-top experiences, Arab heritage and luxury shopping, Dubai rises from the golden sands like a mirage.", detail: "Dubai is a city of superlatives: you can ride the elevator to the top of the world’s tallest building for a bird’s-eye view (that is, until the Burj Khalifa is relegated by Santiago Calatrava’s Tower at Dubai Creek to #2 globally), bet on the ponies at the world’s richest horse race and pose for photos in front of the world’s tallest choreographed fountains. These experiences are not by accident: the city reinvented itself yet again throughout the 2010s, growing from a sterile playground for a handful of ultra-rich Emiratis to an international tourism and business destination. That has helped to attract the second-highest proportion of foreign-born citizens of any city worldwide, and they’re a sharp crowd, ranking #16 for Educational Attainment globally. Dubai’s next challenge will be weathering the storm of COVID-19. Even after a first wave that saw 6,021 cases per million residents, Dubai is hoping to bring back the tourists who have become critical to its economy. In 2019, the city welcomed 16.7 million tourists; it will be lucky to see a fraction of that in 2020, despite a worldwide campaign to reassure visitors of its COVID-19 safety. The most visited mall on the planet is here, and helps Dubai climb to #26 in our Shopping subcategory. It would be a mistake to focus on the “mall” part of the name, however; like the city itself, the Dubai Mall is more of an attempt to capture every human experience and repackage it for consumption. But it’s the outdoors that really clinched Dubai’s #6 overall ranking. The city offers outdoor experiences that rank fifth-most in quality, and it hit the Top 10 for both Safety and Weather, both at #8.", image: "../assets/dubai.jpg" },
      { id: 7, name: 'singapore', country: 'singapore', population: 5745000, summary: "Asia’s financial powerhouse turns its ambitions to elevated infrastructure and homegrown innovation.", detail: "Few cities have achieved as much, as quickly, as the city-state of Singapore has over the past five decades. The meteoric rise from politically unstable, resource-poor and unskilled ex-colony to talent- and capital-hungry shipping hub (the world’s busiest) and, subsequently, Asia’s wealth management capital is place-brand engineering at its most ambitious. The result is Singapore as a fast-emerging Asian financial superpower whose city leaders take a methodical (yes, many would say “heavy-handed”) approach to urban planning that considers needs that reach far beyond the next election. Singapore’s reinvestment into research, talent and corporate headquarters recruitment ensures it will be home to a sustainably wealthy citizenry for decades to come. It’s why the city-state continues its ascent among the planet’s most prosperous cities, with a growing cluster of Global 500 companies (ranking #30 overall). Today, manifestations of this wealth and confident swagger are everywhere. Only in Singapore does an airport become a must-see attraction, one that receives millions of passengers a year but also lures locals with a bounty of designer shops, gardens, gourmet food and one-of-a-kind sights. Opened in 2019 and designed by Safdie Architects, the new $1.7-billion Jewel Changi Airport features a canopy bridge and glass walkway shrouded in fog and suspended 75 feet in the air. But the real showstopper is the seven-story Rain Vortex, an indoor waterfall (the world’s tallest) that cascades down from a central oculus in the roof. Although Singapore lands at #57 for Airport Connectivity, it would medal for its gateway’s experience alone if we scored such things.", image: "../assets/singapore.jpg" },
      { id: 8, name: 'barcelona', country: 'spain', population: 4991133, summary: "The defiant Catalan capital’s intoxicating mix of beach, architecture and creativity has framed the city as the poster child of global overtourism—and its solutions.", detail: "Barcelona is an almost ideal European city, one with near-perfect weather year round, miles and miles of beaches, iconic parks, striking architecture and colorful neighborhoods that march to their own beat—artistic, sophisticated, bohemian. No wonder it ranks Top 10 in our Place category, which measures both the natural and built environments of a city. Steeped in history and wearing its cultural identity proudly on its sleeve, Barcelona is a tourism magnet, often to the dismay of the many locals who see the crowds as a threat to their city. Barcelona has led the world in responding with programs aimed at controlling the effects of runaway tourism—like real estate investors who snatch up apartments only to rent them on Airbnb, depleting an already limited supply. Ultimately the pandemic took care of “the tourist problem,” with devastating results. Infection flare ups meant that tourist sources like France have banned all citizen travel to the Barcelona region and local sources estimate that almost 40% of the shuttered bars and restaurants may never reopen. For a city with the #3 ranking for global Nightlife, this is catastrophic. It’s impossible to predict when it will be once again possible to fuel up on tapas on Las Ramblas to get the night started before exploring hidden speakeasies of Barri Gòtic, Europe’s largest Gothic quarter and the heart of Barcelona, then grabbing an Uber to the industrial-sized clubbing of Port Olímpic. When the world reemerges from the pandemic, Barcelona’s fifth-most TripAdvisor reviews among the world’s cities will surely need a somber rewrite.", image: "../assets/barcelona.jpg" },
      { id: 9, name: 'toronto', country: 'canada', population: 6871000, summary: "Economic growth, fueled by immigration and global investment, have Canada’s largest city poised for big things.", detail: "With almost half of its population foreign-born, Toronto’s #13 spot among the world’s cities—it’s highest finish ever—is powered by diversity and education—the two components of our People category, for which the city ranks #3, just behind Dubai and Abu Dhabi. But Toronto’s diversity is less tied to migrant labor and more to the long-term opportunity in a city that earlier this summer was crowned as the fastest growing metropolitan area in all of North America. As in, the continent. Ryerson University’s Centre for Urban Research and Land Development revealed that Toronto overtook Dallas–Fort Worth–Arlington for the top spot. The city’s openness, combined with its economy (with the eighth-most Global 500 head offices in the world) has resulted in unprecedented density and a satisfaction with just staying put, sated by real estate wealth and the comfort that the world is already in town. Of course, winning an NBA title doesn’t hurt, either.", image: "../assets/toronto.jpg" },
      { id: 10, name: 'rome', country: 'italy', population: 4429025, summary: "The Eternal City has always been coveted. These days, the bounty is an immersive step back in time.", detail: "Few cities serve up the ability to walk the history of the Western world like Roma. Heck, Palatine Hill alone invites you into two millennia of Western civilization, if you’ve got an hour. Mix a safe, accessible modern city and its thousands of portals back in time and it’s easy to see how Rome almost cracked the Best Cities Top 10 again this year. Declarations of love for the city have multiplied with the channels of self-expression, of course, and the city’s #7 ranking in our extensive Place category has directly fueled its #5 Promotion ranking, including the second-most number of TripAdvisor reviews on the planet and very frequent Google searches. The curiosity about the Eternal City will only increase as Rome reopens carefully to visitors, who, after gorging on six months of local ’Grams featuring empty summer streets and iconic sites with nary a tourist umbrella to clutter the shot, are keen to time their return before the crowds come back. As of late summer 2020, most sights were reopened, as were most bars and restaurants. It’s not exactly la dolce vita quite yet, but Roma has persevered once again.", image: "../assets/rome.jpg" },
      { id: 11, name: 'berlin', country: 'germany', population: 5259363, summary: "Germany has evolved into a symbol of tolerance. No other city in the country embodies these sentiments quite like its capital.", detail: "Expats, creatives, entrepreneurs, immigrants, punks and misfits all find their place in Berlin, a city where remnants of a fragile history mingle with an ever-changing present, and where being whatever you want to be is not just encouraged but embraced. Though it was spared the COVID-19 numbers other European capitals experienced during the first wave (possibly thanks to the country’s science-friendly attitude and chancellor) the city still had to cancel its celebration of diversity, Karneval der Kulturen, while the famed Berlin Pride Celebration went virtual. In a normal winter, bars are packed to the gills and techno clubs pulse into the wee hours—the city hits #5 globally for our Nightlife subcategory. As soon as the sun comes out, the entire city heads outdoors, to the parks, the beer gardens and one street party or parade after another. Berlin also ranks #8 for Museums, while its art galleries overflow. This year the crowds will be kept smaller for safety, and masks will be enforced, but no one expects that to dampen the city’s famous cool factor.", image: "../assets/berlin.jpg" },
      { id: 12, name: 'sydney', country: 'Australia', population: 4578000, summary: "Friendly, warm, young and rich, Sydney is a beauty with a growing line of suitors.", detail: "If Sydney weren’t so (relatively) isolated, chances are it would be challenging Paris and London for visitor number supremacy. It’s the laid-back, safe and sunny manifestation of the good life. Let’s use new residents as a benchmark: according to local numbers, Sydney has been gaining more than 80,000 annually, ranking #16 in our People category. Many of those people are foreign-born, too, with a #6 ranking in the subcategory. The city’s staggering growth is indicative of the pull of the golden beaches, the big-city harbor and the mellow, generous, welcoming citizens who call this spectacular location home. Sydney’s big outdoor spaces likely helped the city weather the coronavirus pandemic—within the Top 20, it had the third-fewest cases per million residents—and some green spaces saw double the usual number of visitors. The city is gifted with perfect integration of the natural and built, and accessible by all manner of ferries and watercraft, from which new angles on icons like the Opera House and Sydney Harbour Bridge are revealed.", image: "../assets/sydney.jpg" }
    ]
  }

  constructor() { }
}

然后在app.module.ts 中注册服务。

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { CitiesComponent } from './cities/cities.component';
import { ErrorComponent } from './error/error.component';
import { CitiesService } from './cities.service';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';


@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    CitiesComponent,
    ErrorComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  providers: [CitiesService],
  bootstrap: [AppComponent]
})
export class AppModule { }

在下一步中,我导入了 CitiesService 并在构造函数中将其初始化为home.component.ts 中的服务。

import { Component, OnInit } from '@angular/core';
import { CitiesService } from '../cities.service'



@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  cities: any;
 

  constructor ( private service: CitiesService) {
    this.cities = service.getCities(); 
   }

  ngOnInit (): void {
  
  }  
}

之后,我使用 *ngFor 遍历 home.component.html 中CityService的值。我还添加了一个 [routerLink] 以使用城市名称 (city.name) 传递路由参数。

<div class="body">
    <div class="banner">
       <p class="main">explore the world</p>
    </div>
</div>
<div class="grid">
    <div *ngFor="let city of cities">
        <a [routerLink]="['/cities', city.name]" routerLinkActive="line">
        <div class="wrap">
           <img class="image"  src="{{city.image}}" alt="" class="image">
            <p class="city">{{city.name}}</p>
        </div>
        </a>
    </div>
</div>

在下一步中,我在 app-routing.module 中设置路由,分配一个占位符 (:name) 以匹配 home.component.html 中的值。

import { ErrorComponent } from './error/error.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { CitiesComponent } from './cities/cities.component';


const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'cities/:name',
    component: CitiesComponent
  },
  {
    path: '**',
    component: ErrorComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

当我尝试在下一步中使用 ActivateRoute 生成一个动态组件时,我被卡住了,该组件将在从 home.component.html 中单击时显示国家/地区的详细信息。我将 ActivatedRoute 导入到cities.components.ts组件中,在构造函数中将其初始化为activateroute并编写了以下代码,如下面的屏幕截图所示,但city.component.html 中没有显示任何内容。

import { Component, OnInit } from '@angular/core';
import { CitiesService } from '../cities.service';
import { HomeComponent } from '../home/home.component';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

@Component({
  selector: 'app-cities',
  templateUrl: './cities.component.html',
  styleUrls: ['./cities.component.css']
})
export class CitiesComponent implements OnInit {
  city: any;
  

  constructor ( private service: CitiesService, private activatedroute: ActivatedRoute, city: HomeComponent ) {
    
   }

  ngOnInit () {
    this.city = this.activatedroute.snapshot.paramMap.get( "name" );
  }
}

这是来自city.component.html的代码。拜托,我想知道我在哪里弄错了。

<div>
    <h1>My {{city.name}} is in beautiful</h1>
    <p>{{city.population}}</p>
</div>

标签: javascriptangulartypescript

解决方案


工作 Stackblitz 代码

正如@Yassine Maghfour 所提到的,传递 id 而不是 name 是一种很好的做法,尽管获得重复名称的可能性非常小,但这是可能的。

我还看到您将 HomeComponent 传递给 CityComponent 构造函数。不确定你是否可以做到。并且无法理解为什么您需要在城市中使用家庭组件。


推荐阅读