我正在使用jsonplaceholder创建一个虚拟应用程序,我收到所有帖子,但我无法发布动态ID,如posts / $ {id}。我怎样才能做到这一点。善意的帮助。 我正在使用基本生成角度应用程序。
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<h1>{{title}}</h1>
<!-- -->
<main *ngIf="!some; else elseBlock">
<section *ngFor="let dt of data">
<aside>ID: <span id="id">{{dt.id}}</span></aside>
<aside>Title: {{dt.title}}</aside>
<button (click)="linkto()">click to view</button>
<br>
<hr>
</section>
</main>
<ng-template #elseBlock>
<section>
<aside>ID: {{data2.id}}</aside>
<aside>Title: {{data2.title}}</aside>
<aside>Body: {{data2.body}}</aside>
<button (click)="linkto()">back</button>
<br>
<hr>
</section>
</ng-template>
app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app';
constructor(private http : HttpClient){
this.showPost();
}
data :any = [];
id: any;
data2 :any = {};
some: boolean;
showPost() {
this.http.get('https://jsonplaceholder.typicode.com/posts')
// clone the data object, using its known Config shape
.subscribe(data => {
console.log('**************',data);
this.data = data
});
}
linkto(){
this.showPost2();
this.some = !this.some;
}
showPost2() {
this.http.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
.subscribe(data2 => {
this.data2 = data2;
});
}
}
我也感兴趣,如果有更短的方法吗? 就像一页上的简单。我正在提出请求但在此之后我将发布,放置,修补和删除。在app.component.html页面本身。
答案 0 :(得分:0)
您应使用id
html
向component
发送linkto(dt.id)
然后,您可以在id
方法中将parameter
用作component
。
<强> HTML:强>
<main *ngIf="!some; else elseBlock">
<section *ngFor="let dt of data">
<aside>ID: <span id="id">{{dt.id}}</span></aside>
<aside>Title: {{dt.title}}</aside>
<button (click)="linkto(dt.id)">click to view</button>
<br>
<hr>
</section>
</main>
<ng-template #elseBlock>
<section>
<aside>ID: {{data2.id}}</aside>
<aside>Title: {{data2.title}}</aside>
<aside>Body: {{data2.body}}</aside>
<button (click)="linkto(dt.id)">back</button>
<br>
<hr>
</section>
</ng-template>
<强>组件:强>
linkto(id){
this.showPost2(id);
this.some = !this.some;
}
showPost2(id) {
this.http.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
.subscribe(data2 => {
this.data2 = data2;
});
}