Having Issues Rendering api data in Material Angular Table - html

Good Afternoon,
I am trying to render the api data in a material table, but I am having issues connecting my NasaApiService to the dataSource array.
As of right now I am getting a "Type 'MatTableDataSource' is not assignable to type '[]'. error. Any help is much appreciated.
/*Nasa Service*/
import { Injectable } from '#angular/core';
import {HttpClient } from '#angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
export interface NasaStation {
name: string;
nametype: string;
id: string;
year: string;
recclass: string;
items: any;
}
#Injectable()
export class NasaApiService {
parsed: any;
constructor(private _http: HttpClient) {
}
getNasaData(): Observable<NasaStation> {
return this._http.get<NasaStation>('https://data.nasa.gov/resource/gh4g-9sfh.json');
}
}
/*nasa.component.*/
import { Component, OnInit } from '#angular/core';
import { NasaApiService} from '../nasa-api.service';
import {HttpClient} from '#angular/common/http';
import { MatTable,MatTableDataSource } from '#angular/material/table';
const api = 'https://data.nasa.gov/resource/gh4g-9sfh.json';
#Component({
selector: 'app-nasa',
templateUrl: './nasa.component.html',
styleUrls: ['./nasa.component.css']
})
export class NasaComponent implements OnInit {
data;
dataSource: [];
displayedColumns: string[] = ['Name', 'Name-type', 'ID', 'Year', 'Recclass'];
constructor(private _nasa: NasaApiService) {
}
ngOnInit(){
this._nasa.getNasaData().subscribe(data => {
this.dataSource = new MatTableDataSource(this.data);
this.data = data;
console.log(data);
})
}
}

ngOnInit(){
this._nasa.getNasaData().subscribe(data => {
this.data = data;
this.dataSource = this.data;
console.log(this.dataSource);
})
}
}
Was my final nasa.component code and I just passed datasource into Material Angular.

Related

Using Angular11, how does my HomeComponent retrieve the data provided by the Subject in DataService?

In order to make the data accessible through out the app, I created a new service called the DataService where I want to store my data coming from the API in a Subject.
While I do get the data, I cen see the array of objects in a log from DataService, my array in HomeComponent that should get the data is undefined in the console:
browser inspector console output
I imagine I have some stupid errors in my code, I am a beginer. Could you help me ?
HomeComponent:
import {Component, OnInit, Output} from '#angular/core';
import {DataService} from '../../shared/services/data.service';
import {Subscription} from 'rxjs';
import {Article} from '../../shared/models/article';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
#Output() articles?: Article[];
articleSubscription?: Subscription;
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.dataService.emitArticlesSubject(this.dataService.loadArticles());
this.articleSubscription =
this.dataService.articlesSubject.subscribe(
(articles) => {
this.articles = articles;
}
);
console.log('HOME COMPONENT: ngOnInit: this.articles : ' + JSON.stringify(this.articles));
}
}
DataService:
import { Injectable } from '#angular/core';
import {BehaviorSubject, Subject} from 'rxjs';
import {ArticleService} from './article.service';
import {Article} from '../models/article';
#Injectable({
providedIn: 'root'
})
export class DataService {
articles?: Article[];
message = 'Aucun résultat ne correspond à votre recherche.';
articlesSubject = new Subject<Article[]>();
constructor(private articleService: ArticleService) { }
emitArticlesSubject(action: any): void {
this.articlesSubject.next(action);
}
/**
* Method to be served as a parameter
* to the 'emitArticlesSubject' method
* to load articles sorted by date.
*/
loadArticles(): any {
this.articleService.getAll().subscribe(
data => {
this.articles = data._embedded.articles;
console.log('DataService: loadArticles() : ' + JSON.stringify(this.articles));
},
error => {
console.log('ERROR: DataService not able to loadArticles !' );
}
);
}
/**
* Method to be served as a parameter
* to the 'emitArticlesSubject' method
* to load articles sorted by last activity.
*/
loadArticlesByActivity(): any {
this.articleService.getAllSortedByActivity().subscribe(
data => {
this.articles = data._embedded.articles;
},
error => {
console.log('ERROR: DataService not able to loadArticlesByActivity');
}
);
}
}
ArticleService:
import { Injectable } from '#angular/core';
import {HttpClient, HttpHeaders} from '#angular/common/http';
import {Observable} from 'rxjs';
import {Article} from '../models/article';
import {ResponseEntities} from '../../core/ResponseEntities';
const baseUrl = 'http://localhost:8080/articles';
const queryUrl = '?search=';
const dateUrl = '?sort=date,desc';
#Injectable({
providedIn: 'root'
})
export class ArticleService {
constructor(private http: HttpClient) { }
getAll(): Observable<ResponseEntities<Article[]>> {
return this.http.get<ResponseEntities<Article[]>>(`${baseUrl}${dateUrl}`);
}
getAllSortedByActivity(): Observable<ResponseEntities<Article[]>> {
return this.http.get<ResponseEntities<Article[]>>(`${baseUrl}/${dateUrl}`);
}
search(term: string): Observable<ResponseEntities<Article[]>> {
return this.http.get<ResponseEntities<Article[]>>(`${baseUrl}/${queryUrl}${term}`);
}
get(id: any): Observable<Article> {
return this.http.get<Article>(`${baseUrl}/${id}`);
}
create(data: any): Observable<any> {
return this.http.post(baseUrl, data);
}
update(id: any, data: any): Observable<any> {
return this.http.put(`${baseUrl}/${id}`, data);
}
delete(id: any): Observable<any> {
return this.http.delete(`${baseUrl}/${id}`);
}
deleteAll(): Observable<any> {
return this.http.delete(baseUrl);
}
findByTag(tag: any): Observable<Article[]> {
return this.http.get<Article[]>(`${baseUrl}?tag=${tag}`);
}
}
The problem could be related to subscription in data service.
this.dataService.emitArticlesSubject(this.dataService.loadArticles());
in this line emitArticlesSubject() called. but loadArticles() subscribed to underlaying service. emitArticlesSubject() only call loadArticles() and does not wait for its subscription to get complete. that causes articlss to be undefined. you should use promise in loadArticles() or change your service structures and call ArticleService directly in your HomeComponent.
In your HomeComponent you are console logging the contents of this.articles before the articles have actually been fetched. If you want to log the articles after they have been fetched, you can console log in the subscription instead:
this.articleSubscription =
this.dataService.articlesSubject.subscribe(
(articles) => {
this.articles = articles;
console.log('HOME COMPONENT: ngOnInit: this.articles : ' + JSON.stringify(this.articles));
}
);

Angular 6 error: the data which I am getting from api is in the string format how to parse?

hi want to show the data from my api to my frontend (Angular 6) I am using HttpClient method from angular 6 I am new to angular
the data which I am getting from api is in the string format, I need to parse, below is the response image
this is model.ts
export interface Events {
IE_Incident_Start_Time: string;
IE_Start_time: string;
Title: string;
IE_Start_By: string;
Domain: string;
Impact: string;
IE_BU_Description: string;
}
this is component
enter code here
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { Incident } from '../../shared/incidents.model';
import { DataStorageService } from '../../shared/data-storage.service';
#Component({
selector: 'app-active-incident',
templateUrl: './active-incident.component.html',
styleUrls: ['./active-incident.component.css']
})
export class ActiveIncidentComponent implements OnInit {
incidents: Events[];
constructor(private router: Router, private dataStorageService:
DataStorageService) { }
ngOnInit() {
this.dataStorageService.getIncidents()
.subscribe(
(data: Events[]) => this.incidents = data,
(err: any) => console.log(err),
() => console.log('All done getting incidents')
);
}
this is service
enter code here
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Incident } from './incidents.model';
#Injectable()
export class DataStorageService {
constructor(private http: HttpClient) {}
getIncidents(): Observable<Events[]> {
console.log('Getting all incidents from server');
return this.http.get<Events[]>
('api/url');
}
}
html view
enter code here
<div class="card" *ngFor="let incident of incidents.Events">
<div class="card-header">
<span class="badge badge-danger"></span>{{incident.Title}}
<span class="badge badge-danger"></span>{{incident.Incident_Status}}
</div>
</div>
you can use the way as well
return this.dataStorageService.getIncidents()
.pipe(
map(jsonObj => Object.assign(new Events(), jsonObj),
catchError(error => console.log('Error!'))
);
Yes, you can do it this way.
this.dataStorageService.getIncidents().subscribe((data: Events[]) =>{
data.foreach(()=>{
this.incidents.push(JSON.parse(data));
})
},
(err: any) => console.log(err),
() => console.log('All done getting incidents')
);

How to implement datasource for a datatable in Angular 5

I been trying to follow all the tutorials, and answers that I have found and I just can't make it work yet. Any help is appreciated it. I got this error:
Error: Provided data source did not match an array, Observable, or DataSource
And this is the JSON response I get from the server:
{receivedDate: "2018-05-22T00:00:00", id: "27280371", companyName: "Dark&Stormy", documentType: 11, receipts: Array(1), …}
And this is my code:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, FormControl } from '#angular/forms';
import { HttpClient, HttpHeaders, HttpRequest, HttpEventType, HttpResponse } from '#angular/common/http';
import { Router, ActivatedRoute, ParamMap } from '#angular/router';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import { DataSource } from '#angular/cdk/collections';
import { MatPaginator, MatSort, MatTableDataSource } from '#angular/material';
import { myService } from './../../../api';
import { InputService } from './../input.service';
import { IReceipt } from './../models/receipt.model';
#Component({
selector: 'app-submission-details',
templateUrl: './submission-details.component.html',
styleUrls: ['./submission-details.component.css']
})
export class SubmissionDetailsComponent implements OnInit {
setPaymentMethodForm: FormGroup;
submissionList = [];
errorMessage: string;
private documentId;
receipt: IReceipt;
dataSource = new MatTableDataSource();
displayedColumnsReceipt = ['id', 'fromDate', 'pReference', 'pMethod', 'status', 'valid', 'receipt'];
constructor(
private client: myService.Client,
private fb: FormBuilder,
private inputService: InputService,
private router: Router,
private activatedRoute: ActivatedRoute
) {
this.createForm();
activatedRoute.data
.subscribe(
data => this.documentId = data[this.documentId]
);
}
id: string;
private document: any;
ngOnInit() {
this.activatedRoute.params.subscribe(params => {
if (params['id']) {
this.id = params['id'];
console.log('paramsId: ', this.id);
this.inputService.getDocumentId(this.id)
.subscribe(res => {
this.dataSource = res;
console.log('sub-details.res: ', res);
});
}
});
}
getSubmissionDetails(string): void {
this.client.apiSubmissionGetSubmissionDocumentGet('documentId')
.subscribe(
data => {
this.submissionList = this.submissionList;
console.log('data: ', data);
},
(error: any) => this.errorMessage = <any> error);
}
createForm() {
this.setMethodForm = this.fb.group({
documentId: '',
receiptType: ''
});
}
}
Here
this.dataSource = res;
Whats res? Is it array? If so then
this.dataSource.data = res;

retrieve the method from auth.services.ts to login.component.ts in json

app/auth/auth.services.ts:
import {Injectable} from '#angular/core';
import {Router} from '#angular/router';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {User} from './user';
import {Http, Headers, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class AuthService {
result: any;
constructor(private router: Router, private _http: Http) {}
getUsers() {
return this._http.get('/api/users').map(result => this.result = result.json().data);
}
}
http://localhost:3000/api/users :
{"status":200,"data":[{"_id":"5a63f4da17fc7e9e5548da70","name":"Jonson Doeal"},{"_id":"5a63faf417fc7e9e5548da71","name":"Jonson Bol"},{"_id":"5a64f44de87b3e2f80437c6b","name":"aaaa"}],"message":null}
I would like to retrieve data in json from the getUsers method so that I cancompare values
for () {
if (json_value_name == this.temp) {
}
}
login.component.ts:
import {AuthService} from './../auth/auth.service';
import {Component, OnInit} from '#angular/core';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(
private authService: AuthService
) {}
ngOnInit() {
}
onSubmit() {
this.authService.getUsers();
console.log('this.authService.getUsers() ' + JSON.stringify(this.authService.getUsers()));
}
}
the console returns:
this.authService.getUsers(){"_isScalar":false,"source":{"_isScalar":false},"operator":{}}
I would like it to return in this form:
{"status":200,"data":[{"_id":"5a63f4da17fc7e9e5548da70","name":"Jonson Doeal"},{"_id":"5a63faf417fc7e9e5548da71","name":"Jonson Bol"},{"_id":"5a64f44de87b3e2f80437c6b","name":"aaaa"}],"message":null}
you need to use subscribe
onSubmit() {
this.authService.getUsers().subscribe(data => {console.log(JSON.stringify(data)});
}
Your best bet would something like this:
private myData: any[];
ngOnInit() {
myData = this.authService.getUsers();
}
onSubmit() {
console.log('this.authService.getUsers() ' + JSON.stringify(myData));
}
What you are receiving is the expected result from that method call. The http calls in angular return observables. That means you need to subscribe to what you are returning. Depending on what you are trying to do you may want to restructure your service or component to fully utilize the pattern.
In order to print your data try this in your component:
onSubmit() {
this.authService.getUsers().subscribe((data) => {
console.log(`users ${data}`)
});
}
Hopefully this can get you started on using observables.

Display data from a json object array

I am unable to loop through a json object array and display all data in separate divs.
Currently just using some mock data.
Team.servie.ts:
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '#angular/core';
import { Team } from './team';
#Injectable()
export class TeamService {
private _url = "http://jsonplaceholder.typicode.com/posts"
constructor(private _http: Http){
}
getPost() : Observable<Team[]>{
return this._http.get(this._url)
.map(res => res.json());
}
createPost(post: Team){
return this._http.post(this._url, JSON.stringify(post))
.map(res => res.json());
}
}
Component.ts:
import { Component, OnInit } from '#angular/core';
import { TeamService } from '../team.service';
#Component({
selector: 'About',
templateUrl: './about.component.html',
providers: [TeamService]
})
export class AboutComponent implements OnInit{
data;
isLoading = true;
constructor(private _teamService: TeamService){
/*this._teamService.createPost({userId: 1, title: "a", body: "b"});*/
}
ngOnInit(){
var text = "";
var i = 0;
this._teamService.getPost()
.subscribe(post => {
this.isLoading = false;
this.data = post;
console.log(post[0]);
});
}
}
Team.ts
export interface Team{
userId: number;
id?: number;
title: string;
body: string;
}
component.html:
<div *ngIf="isLoading">Getting data....</div>
<div let displayData of data>
<p> {{ displayData.id }}</p>
</div>
I know I am missing something, but i can't figure out what.
Any tips would be greatly appreciated.
use the *ngFor structureal directive like:
<div *ngFor="let displayData of data">
<p> {{ displayData.id }}</p>
</div>