I am learning Full-stack Angular4, and wanted to know how would I be able to get data from a get call from one component into another so I can relay the data into the html page with {{data.name}}?
I tried importing the component into the other component, then setting an empty object into that component.data which holds the data, but I get a empty object as a response back.
What am I doing wrong?
UPDATE:
my shared service:
import {Injectable} from "@angular/core";
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Rx";
import 'rxjs/add/operator/map';
@Injectable()
export class DataService {
apiData: any;
constructor(private http: Http) {}
fetchData() {
return this.http.get('/api/data').subscribe((data) => {
this.apiData = data.json();
console.log(this.apiData);
})
}
}
target component:
import { Component } from "@angular/core";
import { AllTablesComponent } from '../tables/alltables.component';
import { DataService } from './../data.service';
@Component({
selector: 'app-target',
templateUrl: './target.component.html',
styleUrls: ['./target.component.css']
})
export class TargetComponent {
data: any;
constructor(private dataService: DataService) {
this.data = this.dataService.fetchData();
console.log("inside target component");
console.log(this.data);
}
}
Screenshot of Empty object from component vs actual data from the data service.