Fetched data not rendering in Angular - javascript

I'm trying to fetch data From an API using Angular. I can see in the console log that the data is fetched, however the data doesn't render on the page. Help appreciated.
Here is my code:
app.component.html
<p>{{data.Name}}</p>
<p>{{data.Habitat}}</p>
<p>{{data.Status}}</p>
app.component.ts
import { ApiserviceService } from './Service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'apidata';
data:any;
constructor(private _apiservie:ApiserviceService){}
ngOnInit(){
this._apiservie.getdata().subscribe(res=>{
this.data=res;
console.log(res)
})
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
service.ts
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class ApiserviceService {
constructor(private _http:HttpClient){}
getdata(){
return this._http.get('https://mocki.io/v1/8f823c35-8ae8-4fb5-a84b-cf7dce59c7a7');
}
}

app.component.ts
import { ApiserviceService } from './Service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'apidata';
data:any;
constructor(private _apiservie:ApiserviceService){}
ngOnInit(){
this.getinfo()
}
getinfo(){
this._apiservie.getdata().subscribe(res=>{
this.data=res;
console.log(res)
})
}
}
app.component.html
<div *ngFor="let item of data">
<p>{{item.Name}}</p>
<p>{{item.Habitat}}</p>
<p>{{item.Status}}</p>
</div>

Related

How to pass data from app.component.ts to its app.module.ts in Angular?

Due to the requirements of project I need to send data value dataOne in app.component.ts to its app.module.ts so that I can store it in variable moduleValue. Please refer code below and suggest how can achieve this transfer of data within files.
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'formcheck';
dataOne: any;
getValues(val: any) {
console.warn(val);
this.dataOne = val;
}
}
app.module.ts
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
let moduleValue: any;
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
}
I'd suggest that you declare a variable or an observable in a service, however, since you mentioned that you need to do this within the same files you might want to export a variable from your component and import it into your module like so:
app.component.ts
export class AppComponent {
title = 'formcheck';
dataOne: any;
getValues(val: any) {
console.warn(val);
this.dataOne = val;
DATA = this.dataOne;
}
}
export var DATA = '';
app.module.ts
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DATA } from './app.component';
let moduleValue: any;
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
}
Here is the solution using service, I used BehaviorSubject for dynamic updation of value.
https://stackblitz.com/edit/angular-9pitmh?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fdata.service.ts,src%2Fapp%2Fhello.component.ts

Angular component is not rendering | angular 9.1.3

I am not able to render component header in my application. I don't get any error also. In browser, It shows the header tag also but text present in header.component.html is not shown.
app.modules.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
#NgModule({
imports: [ BrowserModule, FormsModule ],
bootstrap: [ AppComponent ],
declarations: [HeaderComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'project',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Project';
}
app.component.html
<header></header>
<p>
Hello World
</p>
header.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent{
}
Please help me. :'(

Angular 6 service injection exception

I started angular two days ago, i m trying to create a service that will do a get request over my spring boot rest end point and I wish to display the result in my angular app
Here is what i have tried till now
My Service:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { ITweet } from './itweet';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ReactiveTwitterService {
constructor(private http_client: HttpClient, private tweetTag: string) { }
spring_webflux_service_url = 'http://localhost:8081/search';
myTweets: Observable<ITweet[]>;
setTweetTag(tag) {
this.tweetTag = tag;
}
seearchTweets() {
this.myTweets = this.http_client.get<ITweet[]>(this.spring_webflux_service_url + '/' + this.tweetTag);
}
getTweets() {
return this.myTweets;
}
}
As you see I m waiting for tweets as a response so here is My tweet Interface
export interface ITweet {
id: {
text: string,
name: string
};
tag: string;
}
My app module is looking like this
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {HttpClientModule} from '#angular/common/http';
import { FormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SerachBarComponent } from './serach-bar/serach-bar.component';
import { SearchReasultComponent } from './search-reasult/search-reasult.component';
import { HeaderComponent } from './header/header.component';
import { ResultItemComponent } from './result-item/result-item.component';
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
SerachBarComponent,
SearchReasultComponent,
ResultItemComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I googled that there is no need for setting my service in providers thanks to providedIn directive in the service implementation
The components where i use this service
import { Component, HostListener } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
innerWidth: number;
styleClass = {
wide_screen: 'w3-light-grey',
break_point: 'w3-dark-grey'
};
#HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
getStyle() {
return (innerWidth > 769) ? this.styleClass.wide_screen : this.styleClass.break_point;
}
}
AND
import { Component, OnInit, HostListener } from '#angular/core';
import { ReactiveTwitterService } from '../reactive-twitter.service';
#Component({
selector: 'app-serach-bar',
templateUrl: './serach-bar.component.html',
styleUrls: ['./serach-bar.component.css']
})
export class SerachBarComponent implements OnInit {
innerWidth: number;
constructor(private twiterService: ReactiveTwitterService) { }
placeholder = 'search';
styleClass = {
wide_screen: 'w3-input w3-light-grey',
break_point: 'w3-input w3-white'
};
doSearch(tag) {
this.twiterService.setTweetTag(tag);
this.twiterService.seearchTweets();
}
ngOnInit() {
}
#HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
getStyle() {
return (innerWidth > 769) ? this.styleClass.wide_screen : this.styleClass.break_point;
}
}
AND
import { Component, OnInit, HostListener } from '#angular/core';
import { ReactiveTwitterService } from '../reactive-twitter.service';
import { ITweet } from '../itweet';
#Component({
selector: 'app-search-reasult',
templateUrl: './search-reasult.component.html',
styleUrls: ['./search-reasult.component.css']
})
export class SearchReasultComponent implements OnInit {
search_result: ITweet[];
innerWidth: number;
constructor(private _twitterService: ReactiveTwitterService) { }
styleClass = {
wide_screen: 'w3-ul w3-hoverable',
break_point: 'w3-green w3-container'
};
ngOnInit() {
this._twitterService.getTweets().subscribe(tweet => this.search_result = tweet);
}
is_search_result_empty() {
return this.search_result === [];
}
set_search_result_empty() {
this.search_result = [];
}
#HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
get_list_style() {
return (innerWidth > 769) ? this.styleClass.wide_screen : this.styleClass.break_point;
}
}
My templates are
AppComponent
<div class="{{getStyle()}}" style="width: 100%;height: 100%;">
<app-header></app-header>
<app-serach-bar></app-serach-bar>
<app-search-reasult></app-search-reasult>
</div>
SearchBar
<div class="w3-container w3-margin-top">
<input class="{{getStyle()}}" type="text" placeholder="{{placeholder}}" (onclick.enter)="doSearch(searchinput.value)" #searchinput>
</div>
Search Result
<div class="w3-container" *ngIf="!is_search_result_empty">
<ul class="{{get_list_style()}}">
<app-result-item *ngFor="let current_item of search_result; trackBy:current_item.id" [item]="current_item"></app-result-item>
</ul>
</div>
the console log an exception and everything is blank
What should i do to fix this ??
you need to add the service to the providers in the module of course remember to import the service
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
SerachBarComponent,
SearchReasultComponent,
ResultItemComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [
ReactiveTwitterService
],
bootstrap: [AppComponent]
})
in your code constructor(private _twitterService: ReactiveTwitterService) { } there is no way to initialize the private tweetTag: string therefore it still fail, and the #Injectable({ providedIn: 'root' }) does not act the same as providers: [ReactiveTwitterService]
Your service should be made available to your component or the module as a provider.
You can add it to providers: array at appmodule or to the individual module and inject it in component for use.

Uncaught Error: Template parse errors: Angular 4

I have been trying to make a simple app in Angular, I was able to make it work in Plunker. Unfortunately, it gives me this error
Can't bind to 'joke' since it isn't a known property of 'app-root'.
that I don't know how to handle.
What is the problem?
joke.component.ts
import { Component, EventEmitter, Input, Output, OnInit } from '#angular/core';
import { Joke } from '../jokes'
#Component({
selector: 'app-joke',
templateUrl: './joke.component.html',
styleUrls: ['./joke.component.css']
})
export class JokeComponent implements OnInit {
constructor() {}
#Input("joke") joke: Joke;
#Output() jokeDeleted = new EventEmitter<Joke>();
deleteItem() {
this.jokeDeleted.emit(this.joke)
}
ngOnInit() {}
}
joke-form.component.spec
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { JokeFormComponent } from './joke-form.component';
describe('JokeFormComponent', () => {
let component: JokeFormComponent;
let fixture: ComponentFixture<JokeFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ JokeFormComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JokeFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
joke-list.component
import { Component, OnInit } from '#angular/core';
import {Joke} from '../jokes';
#Component({
selector: 'app-joke-list',
templateUrl: './joke-list.component.html',
styleUrls: ['./joke-list.component.css']
})
export class JokeListComponent implements OnInit{
jokes: Joke[];
constructor() {
this.jokes = [
new Joke("I am telling a joke.", "Haha, that's funny!"),
new Joke("I am telling an even funnier joke.", "Hahahahaha!!"),
new Joke("I am telling the funniest joke.", "HAHAHAHAHAHA!!!!")
]
}
addJoke(joke) {
this.jokes.unshift(joke);
}
deleteJoke(joke) {
let indexToDelete = this.jokes.indexOf(joke)
if (indexToDelete !== -1) {
this.jokes.splice(indexToDelete, 1);
}
}
ngOnInit() {}
}
app.component
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { JokeFormComponent } from './joke-form/joke-form.component';
import { JokeListComponent } from './joke-list/joke-list.component';
import { JokeComponent } from './joke/joke.component';
#NgModule({
declarations: [
AppComponent,
JokeFormComponent,
JokeListComponent,
JokeComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
From the code you have posted I see that your AppComponent class is empty :
export class AppComponent {}
Since you haven't posted your html code, I am guessing you are doing something similar to the plunker, where my-app in plunker is equivalent to app-root in your question's code:
<app-root *ngFor="let j of jokes" [joke]="j" (jokeDeleted)="deleteJoke($event)"></app-root>
Once you add #Input("joke") joke: Joke to AppComponent class, it should not throw that error anymore:
export class AppComponent {
#Input("joke") joke: Joke;
#Output() jokeDeleted = new EventEmitter<Joke>();
deleteItem() {
this.jokeDeleted.emit(this.joke)
}
}
You can try to delete this OnInit method that angular generates for us in this child joke.component.ts class that implements this #Input method for Property binding [property]. And also restart the server.

Javascript Angular4 Service method not recognize

I have created a simple service using angular4
Here's the code:
//app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { MyserviceService } from './myservice.service';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
//the service
import { Injectable } from '#angular/core';
#Injectable()
export class MyserviceService {
constructor() { }
cars = ['fiat', 'form'];
myData() {
return 'Hello from service!';
}
}
//app.component.ts
import { Component, OnInit } from '#angular/core';
import { MyserviceService } from './myservice.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
constructor(private myservice: MyserviceService) {}
ngOnInit() {
console.log(this.myservice.cars);
this.something = this.myData();
}
}
I am having 2 problems here:
No console message
myData is not recognized 'myData does not exists in app.component'
What I'm I doing wrong here?
You are accessing myData() method on app.component, it is not a member of app component. you have to access myData() with myservice, like this
ngOnInit() {
console.log(this.myservice.cars);
this.something = this.myservice.myData();
}
and Everything else looks fine to me.

Categories

Resources