【问题标题】:Display countries, states and cities in different components using routing in angular使用角度路由显示不同组件中的国家、州和城市
【发布时间】:2019-06-07 09:24:18
【问题描述】:

我有一个国家和城市的 json。我想在国家组件上显示第一个国家列表,在州组件上显示州列表,然后在城市组件上显示城市。

请帮助我如何以 6/7 角度显示父子(多级)的数据。

JSON 数据 -

{
"country": [{
    "id": 1,
    "countryName": "India",
    "state": [{
        "id": 11,
        "stateName": "Andhra Pradesh",
        "city": [
            "Anantapur",
            "Chittoor",
            "East Godavari",
            "Guntur",
            "Krishna",
            "Kurnool",
            "Nellore",
            "Prakasam",
            "Srikakulam",
            "Visakhapatnam",
            "Vizianagaram",
            "West Godavari",
            "YSR Kadapa"
        ]
    }]
}]

}

国家组成部分 - 这里显示国家列表,点击列表后显示其特定的州城市。

<ul>
   <li *ngFor="let x of country">{{x.countryName}}</li>
</ul>

【问题讨论】:

  • 到目前为止您尝试了什么?您可以创建一个 stackblitz 并为您的问题添加一个链接。

标签: angular


【解决方案1】:

TLDR;您正在寻找的几乎是基本的angular tutorial

入口点是您的country.component.ts 并仅获取数据而不是每个组件上的数据。所以你应该提供服务DataService。在那里你应该推送你的 json-data。你所有的 json 条目都有 id,所以我会在路由中给出 id

<ul>
   <li *ngFor="let country of countries" [routerLink]="['states',country.id]">{{country.name}}</li>
</ul>

在此之后,您的 states.component.ts 应该看起来相同,但您使用的是州和城市,而不是国家和州。

<ul>
   <li *ngFor="let state of states" [routerLink]="['cities',state.id]">{{state.name}}</li>
</ul>

states.component 中,您构建服务并在您的国家/地区数组中搜索正确的对象以获得您需要的状态。

export class StateComponent implements OnInit {

    country : any; //again or model Country
    id: number;
    private sub: any;

  constructor(
    private route : ActivatedRoute,
    private dataService : DataService,
  ) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = +params['id']; // (+) converts string 'id' to a number
    });

      this.dataService._data
      .subscribe(
        next => {
          this.country = _data.find(id); //search logic here inside array countries for your country with id, use the normal js find
        },
        () => {
          console.log('Error');
        },
        () => {
          console.log('Complete');
        }
      );
  }
  }

您的路由模块中的路径应如下所示:

  {
    path: 'states/:id',
    component : StatesComponent,
  },
       {
    path: 'cities/:id',
    component : CitiesComponent,
  }

您可以将所有这些路径设置为children。适合您的关键字:带有可观察对象的服务。

DataService 就像:

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

    private dataSource = new BehaviorSubject(undefined);
    _data = this.dataSource.asObservable();

    constructor(){}

    setDataSource(jsonData : any) {
        this.dataSource.next(jsonData);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2012-11-02
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多