I am creating a simple application which for now only has two pages:
(1) A full list of stocks. (2) Details about a single stock.
When you click on a specific stock in the list of stocks, you should be routed to the other page to read its info.
Here is the service I use:
export class StockService {
stock$ = new Subject();
public setStock(stock: Stock){
this.stock$.next(stock);
}
public getStock():Observable<any>{
return this.stock$.asObservable();
}
constructor() { }
}
On my page (1) I have the following HTML:
<div >
<app-stock-object
*ngFor="let stock of stocks"
[stock] = "stock"
(click)="setSelected(stock)"
routerLink="/stock-details">
</app-stock-object>
</div>
And the following class in TS
export class StocksComponent implements OnInit {
@Input() stocks: Stock[] = Stock_data;
constructor(private stockService: StockService) { }
ngOnInit(): void {
}
public setSelected(stock: Stock){
this.stockService.setStock(stock);
}
}
The second page where I (try to) retrieve the stock:
export class StockDetailsComponent implements OnInit {
//Initilialising without a value ...
stock: any;
constructor(private stockService: StockService) { }
ngOnInit(): void {
this.stockService.getStock().subscribe(stock=>{
//The message below is shown with the selected stock.
console.log("stock -->",stock);
this.stock = stock;
})
}
}
and the HTML:
<p>the stock details are: {{stock?.name}}</p>
I think that it is because I initialise the stock without a value to declare its type. I am new to Angular and am therefore having issues seeing what the best solution would be to solve this. Thanks in advance!
CodePudding user response:
Please try using BehaviorSubject instead of Subject as Behavior Subject will give you last emitted value even if you subscribe in future. For eg :-
stock$ = new BehaviorSubject(null);