【发布时间】:2020-04-13 10:10:26
【问题描述】:
我有一个通过 Httpclient 获取的请求。我遇到的问题是当我尝试访问由其他组件的此请求加载的此变量时。 当我尝试这样做时,我发现它是空的。
这是服务中的方法:
import { HttpClient } from '@angular/common/http';
...
getBooks(page: string) {
let url = `${this.urlAPI}books?page=${page}`;
return this.http.get<Book[]>(url).pipe(map((res: Book[]) => res));
}
这是component.ts中的代码。它是递归的,因为 api 每次只加载 50 个。
import { ApiService } from 'src/app/services/api.service';
...
books: Book[] = [];
...
constructor(public auth: AuthService, public _api: ApiService, private router: Router) {
this.loadBooks(1);
}
...
loadBooks(page: number) {
this._api.getBooks(page.toString()).subscribe((resp: Book[]) => {
this.books = this.books.concat(resp);
if (resp.length !== 0)
this.loadBooks(page + 1)
else{
...
}
});
}
这是从子组件加载变量的方法:
import { Component, OnInit, Input } from '@angular/core';
import { BooksComponent } from '../../tab/books/books.component';
...
import { ApiService } from 'src/app/services/api.service';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.scss'],
providers: [BooksComponent]
})
export class BookComponent implements OnInit {
book: Book = new Book();
constructor(private bc:BooksComponent, public _api: ApiService, private route: ActivatedRoute) {
console.log(bc.books);
...
}
在父组件之后对子组件的调用。我也知道这是异步调用,所以在它没有完成之前,我还没有填充变量。但是我在查看父组件中的所有数据后调用它。 我不明白为什么如果我填充了变量,这个数组对于其他组件是空的。 谢谢你的回答。
更新: 这是我用来调用书籍组件的 HTML:
<ng-container matColumnDef="detail">
<th mat-header-cell *matHeaderCellDef> Details </th>
<td mat-cell *matCellDef="let row">
<button mat-button (click)="detail(row.url)">
<mat-icon>info</mat-icon>
</button>
</td>
</ng-container>
它是角材料表的一部分。我使用该功能去预订组件。
这是 NgModule:
@NgModule({
declarations: [
AppComponent,
HomeComponent,
ListComponent,
NavbarComponent,
ProfileComponent,
BooksComponent,
BookComponent
],
imports: [
BrowserModule,
AppRoutingModule,
APP_ROUTING,
MaterialModule,
HttpClientModule
],
providers: [ApiService],
bootstrap: [AppComponent]
})
export class AppModule { }
父组件是第二个代码。其余代码是关于 MatPaginator、MatSort 或 MatTableDataSource。
更新 2:
我将代码留在 GitHub 中:WikiIceAndFire
【问题讨论】:
-
哦,顺便说一句,
this.http.get<Book[]>(url).pipe(map((res: Book[]) => res))没有任何意义 - 您正在“映射”到原始值。你应该把它改成this.http.get<Book[]>(url); -
是的,嘿嘿,我忘了取下来。谢谢
标签: angular httpclient angular-components