从本地json获取具有ID的单个数据

时间:2019-03-25 13:50:30

标签: javascript json angular ionic-framework ionic4

  

我正在使用ionic 4构建列表应用。所有项目列表视图均来自本地    json,但ID单一的项无法从本地json获取

app-routing.module.ts

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

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: './home/home.module#HomePageModule' },
  { path: 'details/:id', loadChildren: './details/details.module#DetailsPageModule' },
];

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

home.page.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import {map} from 'rxjs/operators';
import { Observable } from 'rxjs';
import { RecipiService } from '../services/recipi.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  //  jsons:any;


  constructor(private recipiservice:RecipiService ){
    this.recipiservice.getData();
  }
}

details.page.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { RecipiService } from '../services/recipi.service';

@Component({
  selector: 'app-details',
  templateUrl: './details.page.html',
  styleUrls: ['./details.page.scss'],
})
export class DetailsPage implements OnInit {
  information = null ;

  constructor(private activatedRoute:ActivatedRoute,private recipiservice:RecipiService) { }

  ngOnInit() {
    let id = this.activatedRoute.snapshot.paramMap.get('id');
    this.recipiservice.getDetails(id).subscribe(result =>{
      console.log('details', result)
      this.information = result;
    });
  }

}

recipi.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class RecipiService {
  jsons: any;
  url = '/assets/resource.json';


    //json:any;
   constructor(private http:HttpClient) {}

  getData(){

    let data: Observable<any> = this.http.get(this.url);
    data.subscribe(results =>{
      // console.log(this.jsons);
        return this.jsons = results;
    })
}

getDetails(id){
   //console.log(id);
   return this.http.get(this.url); //how to get single item with id & this line code not complate . please help me for complate my code 
}
}
  

这里所有项目都获得。但是我去了单项项目

here all item get . but i went get to singel item

  

喜欢,获得ID为ID的单项

Like it, get single item with id

这是离子4应用。这是离子4应用。这是离子4应用。这是离子4应用。这是离子4应用。这是离子4应用。这是离子4应用。

1 个答案:

答案 0 :(得分:1)

您可以在服务代码中执行以下操作:

===

}

由于我使用的是id进行比较,因此请确保您将getDetails传递给id,并确保每个项目中服务器响应中的{{1}}属性具有相同的数据类型。即两者都应该是数字,或者都应该是字符串值。

Stackblitz Working Example

希望这会有所帮助。