gpt4 book ai didi

javascript - 如何在 Angular 中使用通过状态传递的数据

转载 作者:行者123 更新时间:2023-11-28 16:54:47 25 4
gpt4 key购买 nike

我正在尝试在我的 Angular 应用程序中实现搜索,通过图书服务接收数据,并在导航到新组件时使用状态传递数据,数据采用对象数组的形式。我这里的挑战是如何使用新组件上的数据,下面的方法没有给我所需的结果。

搜索输入

import {
Component,
OnInit
} from '@angular/core';
import {
BookService
} from '../services';
import {
Router
} from '@angular/router';

@Component({
selector: 'search-input',
templateUrl: `
<form (ngSubmit)="searchBooks(searchTerm)">
<input type="search" [(ngModel)]="searchTerm" name="searchTerm" Search" aria-label="Search">
</form>
`,
styleUrls: ['./navbar.component.css']
})
export class SearchInputComponent implements OnInit {
searchTerm = '';
foundBooks: any;

constructor(private bookService: BookService, private router: Router) {}

ngOnInit() {}

searchBooks(searchTerm) {
this.bookService.searchBooks(searchTerm)
.subscribe(books => {
this.foundBooks = books;
console.log(this.foundBooks);
this.router.navigateByUrl('search-output', {
state: {
result: this.foundBooks
}
});
});

}

}

搜索输出

import {
Component,
OnInit
} from '@angular/core';
import {
ActivatedRoute
} from '@angular/router';
import {
Observable
} from 'rxjs';
import {
map
} from 'rxjs/operators';

@Component({
selector: 'app-search-output',
templateUrl: `
<div *ngFor="let state of state$">
<p>{{state}}</p>
</div">
`,
styleUrls: ['./search-output.component.css']
})
export class SearchOutputComponent implements OnInit {
state$: Observable < object > ;

constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {
this.state$ = this.activatedRoute.paramMap
.pipe(map(() => window.history.state));

// console.log(this.state$);

}

}

最佳答案

您可以通过两种方式实现这一目标。

  1. 使用服务这是最好的方法
  2. 使用路由
  1. Using service: just make setter and getter method in service

service.ts

<小时/>
bookData: any = [];

setData(data) { // call this method from the component and pass the result you get from the API to set it in the service
this.bookData = data;
}


getData(data) { // call this method from the component to get the already set data
return this.bookData;
}
<小时/>
  1. Using Routing:

搜索输入

 searchBooks(searchTerm) {
this.bookService.searchBooks(searchTerm)
.subscribe(books => {
this.foundBooks = books;
console.log(this.foundBooks);
this.router.navigate(['/component2', {result: this.foundBooks}]); // private router: Router => import Router

});

}

搜索输出

  ngOnInit() {
console.log(this.route.snapshot.paramMap.get('result')); //private route: ActivatedRoute /=> import ActivatedRoute

}

关于javascript - 如何在 Angular 中使用通过状态传递的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59420837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com