In the displayresults component, I'm trying to pass the response I get from the http.get() to the articleinfo component.
I was originally doing this by using queryParams but I need to pass more complex information from my JSON such as other objects and arrays. I'm using the ArticleInformationService to set the response using this.article_info.setJSONData(response);
and then I use console.log(this.article_info.getJSONData());
to make sure I'm getting the right data and I am. But now when I go into the articleinfo component and try console.log(article_info.getJSONData());
I get an empty object. My assumption is that article_info
inside the articleinfo component doesn't see its value from displayresults because it is a new instance? Am I going about this the right way?
Component 1
import { Component, OnInit } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Router, NavigationExtras } from "@angular/router";
import { ArticleInformationService } from "../article_information/article-information.service";
@Component({
selector: "app-displayresults",
templateUrl: "./displayresults.component.html",
styleUrls: ["./displayresults.component.css"],
providers: [ArticleInformationService]
})
export class DisplayresultsComponent implements OnInit {
response: any;
constructor(
private http: HttpClient,
private router: Router,
private article_info: ArticleInformationService
) {}
ngOnInit() {
this.search();
}
search() {
var query: string = window.location.search.substring(1).split("=")[1];
this.http
.get(
"http://my.json/_search?q=" +
query +
"&size=100"
)
.subscribe(response => {
this.response = response;
//*******Setting the response to the service atttribute
this.article_info.setJSONData(response);
console.log(response);
console.log(this.article_info.getJSONData());
});
}
Component 2
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { ArticleInformationService } from "../article_information/article-information.service";
@Component({
selector: "app-articleinfo",
templateUrl: "./articleinfo.component.html",
styleUrls: ["./articleinfo.component.css"],
providers: [ArticleInformationService]
})
export class ArticleinfoComponent implements OnInit {
constructor(article_info: ArticleInformationService) {
console.log(article_info.getJSONData());
}
ngOnInit() {}
}
Service
import { Injectable } from "@angular/core";
@Injectable({
providedIn: "root"
})
export class ArticleInformationService {
jsonData;
constructor() {
this.jsonData = {};
}
setJSONData(val: object) {
this.jsonData = val;
}
getJSONData() {
return this.jsonData;
}
}