【发布时间】:2021-03-16 16:08:10
【问题描述】:
我无法将数据从一个组件显示到另一个组件。 我将我从服务中获取的数据放入 prova 并显示所有工作的列表。但我无法将“prova”上的数据传输到另一个组件,以通过它们自己的 id 显示详细信息。
这是我的 apicall 服务
import { Injectable } from '@angular/core';
import {HttpClient,HttpClientModule,HttpResponse} from '@angular/common/http';
import {Observable} from "rxjs";
import {map} from "rxjs/operators";
import {results} from "./results"
@Injectable({
providedIn: 'root'
})
export class GetApiService {
constructor(
private http:HttpClient,
) { }
apiCall():Observable<results[]>
{
return this.http.get('https://www.themuse.com/api/public/jobs?category=Engineering&page=10')
.pipe(map
(
(response:any) => {
const data = response.results;
console.log (data)
return data ;
}
)
);
}
}
这是我观察到的结果
export interface results
{
categories : any;
company: string;
contents:string;
id : number;
levels:string;
locations:string;
model_type: string;
name: string;
refs: string;
short_name: string;
type:string;
}
这是我的组件,其中有一个作品列表
import {results} from "../results";
import {GetApiService} from '../get-api.service';
import {switchMap} from "rxjs/operators";
import { Observable } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-work-list',
templateUrl: './work-list.component.html',
styleUrls: ['./work-list.component.css']
})
export class WorkListComponent implements OnInit {
prova: results[]=[] ;
item: any;
selectedId: any ;
constructor(
private api :GetApiService,
private route: ActivatedRoute,
) { }
ngOnInit(){
this.api.apiCall()
.subscribe
(
(data:results[]) => {
this.prova=data;
console.log (data);
});
}
}
以及通过 id 连接的相应 html
<div *ngFor="let item of prova "
[class.selected]="item.id === selectedId">
<a
[routerLink]="['/details',item.id]">
<h1> {{ item.name }}</h1>
</a>
<h1> {{ item.id }}</h1>
<h1> {{ item.categories[0].name }}</h1>
<h1> {{ item.name }}</h1>
</div>
这是我无法用自己的详细信息显示所选作品的详细信息
import { ActivatedRoute } from '@angular/router';
import {results} from '../results';
import {GetApiService} from '../get-api.service';
import {switchMap} from "rxjs/operators";
@Component({
selector: 'app-work-details',
templateUrl: './work-details.component.html',
styleUrls: ['./work-details.component.css']
})
export class WorkDetailsComponent implements OnInit {
@Input()
item: {
categories: any;
company: string;
contents: string;
id: number;
levels: string;
locations: string;
model_type: string;
name: string;
refs: string;
short_name: string;
type: string;
} | undefined;
@Input ()
prova: results[]=[];
selectedId:string | undefined;
constructor(
private route: ActivatedRoute,
private api: GetApiService,
) { }
ngOnInit():void {
this.route.paramMap.subscribe
(params => {
this.item=this.prova[+params.get('selectedId')];
**// it should be somewthing like this but prova is empty.**
})
;
}
}
【问题讨论】:
标签: angular api components observable