角度:行为主题价值不持续服务
我已经创建了2个组件“搜索栏”和“搜索文量”和一个共享服务“搜索量”。 以下是我的代码: (注意):组件没有孩子和父母的关系。我只是试图使用行为主题在组件之间进行交流,并以新的结果刷新我的UI。
“搜索results.service”:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SearchResultsService {
// Subject to subscribe to
private results = new BehaviorSubject(null);
private productsData;
constructor(private http:HttpClient) { }
// Http Headers
httpOptions : Object = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
bodyJson = {};
RESULTS_API_ENDPOINT = "API_END_POINT_URL";
getResults() {
this.getAPIResults();
return this.results.asObservable();
}
getAPIResults() {
this.http.post(this.RESULTS_API_ENDPOINT , this.bodyJson, this.httpOptions).subscribe(res => this.results.next(res));
}
}
“搜索results.component.ts”
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { Observable, Subject, throwError } from 'rxjs';
import { SearchResultsService } from '../../services/search-results.service';
@Component({
selector: 'app-search-results',
templateUrl: './search-results.component.html',
styleUrls: ['./search-results.component.css'],
providers: [SearchResultsService]
})
export class SearchResultsComponent implements OnInit {
public productsData: Object;
constructor(private resultsService: SearchResultsService) {}
ngOnInit() {
this.resultsService.getResults().subscribe((res) => (this.productsData = res));
}
}
<div *ngFor="let product of productsData.products;">
<h3 class="vs-product-title">
<a [href]="product.productDetailPage">
{{product.name}}>
</a>
</h3>
</div>
“搜索bar.component.ts”
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { SearchResultsService } from '../../services/search-results.service';
@Component({
selector: 'app-search-bar',
templateUrl: './search-bar.component.html',
styleUrls: ['./search-bar.component.css'],
providers: [SearchResultsService]
})
export class SearchBarComponent implements OnInit {
searchForm: FormGroup;
searchTerm: string;
newData: Object = {};
constructor(private resultsService: SearchResultsService) { }
ngOnInit(): void {
this.searchForm = new FormGroup({
searchField: new FormControl()
});
this.resultsService.getResults();
}
Submit() {
this.searchTerm = this.searchForm.value.searchField;
this.resultsService.bodyJson["query"] = this.searchTerm;
this.resultsService.getResults();
}
}
<form class="searchBar vs-col-lg-9" [formGroup] ="searchForm" (ngSubmit)="Submit()">
<label for="searchField">Search Products</label>
<input formControlName = "searchField" aria-label = "Search Products" id="search_products" class = "vs-input" type="text" name= "searchProducts" placeholder= "Search placeholder"/>
<span class="search-icon" (click) = "Submit()"></span>
</form>
当我在检查员中调试时,我会看到将API数据添加到主题中。但是,我的HTML并未在搜索量组件中使用产品数据进行更新。请建议。这是我第一次使用行为主题
i've created 2 components "search-bar" and "search-results" and a shared service "search-results".
below is my code:
(NOTE): components do not have child and parent relationship. i'm only trying to use behavior Subject to communicate between components and refresh my ui with new results.
"search-results.service":
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SearchResultsService {
// Subject to subscribe to
private results = new BehaviorSubject(null);
private productsData;
constructor(private http:HttpClient) { }
// Http Headers
httpOptions : Object = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
bodyJson = {};
RESULTS_API_ENDPOINT = "API_END_POINT_URL";
getResults() {
this.getAPIResults();
return this.results.asObservable();
}
getAPIResults() {
this.http.post(this.RESULTS_API_ENDPOINT , this.bodyJson, this.httpOptions).subscribe(res => this.results.next(res));
}
}
"search-results.component.ts"
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { Observable, Subject, throwError } from 'rxjs';
import { SearchResultsService } from '../../services/search-results.service';
@Component({
selector: 'app-search-results',
templateUrl: './search-results.component.html',
styleUrls: ['./search-results.component.css'],
providers: [SearchResultsService]
})
export class SearchResultsComponent implements OnInit {
public productsData: Object;
constructor(private resultsService: SearchResultsService) {}
ngOnInit() {
this.resultsService.getResults().subscribe((res) => (this.productsData = res));
}
}
<div *ngFor="let product of productsData.products;">
<h3 class="vs-product-title">
<a [href]="product.productDetailPage">
{{product.name}}>
</a>
</h3>
</div>
"search-bar.component.ts"
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { SearchResultsService } from '../../services/search-results.service';
@Component({
selector: 'app-search-bar',
templateUrl: './search-bar.component.html',
styleUrls: ['./search-bar.component.css'],
providers: [SearchResultsService]
})
export class SearchBarComponent implements OnInit {
searchForm: FormGroup;
searchTerm: string;
newData: Object = {};
constructor(private resultsService: SearchResultsService) { }
ngOnInit(): void {
this.searchForm = new FormGroup({
searchField: new FormControl()
});
this.resultsService.getResults();
}
Submit() {
this.searchTerm = this.searchForm.value.searchField;
this.resultsService.bodyJson["query"] = this.searchTerm;
this.resultsService.getResults();
}
}
<form class="searchBar vs-col-lg-9" [formGroup] ="searchForm" (ngSubmit)="Submit()">
<label for="searchField">Search Products</label>
<input formControlName = "searchField" aria-label = "Search Products" id="search_products" class = "vs-input" type="text" name= "searchProducts" placeholder= "Search placeholder"/>
<span class="search-icon" (click) = "Submit()"></span>
</form>
when i debug in inspector, i see the API data being added to the subject. but, my html is not being updated with products data in search-results component. please advice. this is my first time using Behavior Subject
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在提供
提供商:[SearchResultsService]
在两个组件中,将其注入根部。
删除
提供商:[searchResultsService]
来自两个组件。尝试一下,让我知道是否有效。You are providing
providers: [SearchResultsService]
In both components, when it is injected into root.
Remove
providers: [SearchResultsService]
from both components. Give that a try and let me know if that works.“ search-bar.component.ts”文件调用getapiresults()函数而不是getResults()
“ search-results.service”文件删除此行this.getapiresults()
"search-bar.component.ts" file call the getAPIResults() function instead of getResults()
"search-results.service" file remove this line this.getAPIResults()