Uncaught Error: Template parse errors: Angular 4 - javascript

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.

Related

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.

angular2 websocket error: Cannot read property 'subscribe' of undefined

I am using angular-cli.
I am trying to implement this example:
https://www.npmjs.com/package/angular2-websocket-service
I have created my service, and I want to use it directly in AppComponent.
This is what I have:
app/app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { WebSocketService } from 'angular2-websocket-service'
import { MyWebsocketService } from './websocket/mywebsocket.service';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
WebSocketService,
MyWebsocketService
],
bootstrap: [AppComponent]
})
export class AppModule { }
app/app.component.ts
import { Component, OnInit } from '#angular/core';
import {MyWebsocketService} from './websocket/mywebsocket.service'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'title';
constructor(private mywebsocket: MyWebsocketService) { }
ngOnInit() {
this.mywebsocket.connect();
}
}
app/websocket/mywebsocket.service.ts
import { Injectable } from '#angular/core';
import { WebSocketService } from 'angular2-websocket-service'
import { Observable } from 'rxjs/Observable'
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/share'
#Injectable()
export class MyWebsocketService {
private q: Observable<any>
private w: Observable<any>
constructor(private socketFactory: WebSocketService) { }
public connect() {
this.q = new Observable<any>()
this.w = this.socketFactory.connect('ws://localhost:8080/myapp/cswebsocket', this.q).share()
this.w.subscribe()
}
}
And here is what I get:
> core.js:1350 ERROR TypeError: Cannot read property 'subscribe' of
> undefined
Why would this.w be undefined? How can I solve this?

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.

Emit events between nested components grandchild to root component

I have wheels.component nested to car.component.
wheels.component:
export class WheelsComponent {
#Output() onLoaded : EventEmitter<string>() = new EventEmitter<string>();
private downloadAllFiles(url: string) {
this.onLoaded.emit('Hello, World 1!');
//some operations to wait
this.onLoaded.emit('Hello, World 2!');
};
}
Component car.component is not written at html page, but called through routing at car-routing.module.ts:
#NgModule({
imports: [
RouterModule.forChild([
{
path: 'sfactmessage/:id',
component: CarComponent,
resolve: {
card: cardResolver
}
}
])
],
exports: [RouterModule]
})
export class CarRoutingModule {}
What I want is to handle event emitted from wheels.component, not at car.component, but at app.component.
Is it possible to handle event at app.component?
The plunker sample is not working (sorry, this is my first plunkr example), but gives a view how my app is arranged.
Hello_ friend.
So basically if you want to use events globally in your application you can use a Service in combination with EventEmitter
In this case you create a service for example car.service.ts
import { Injectable, EventEmitter } from '#angular/core';
#Injectable()
export class CarService {
onLoaded : EventEmitter<string> = new EventEmitter<string>();
}
Then use this service in a child component to emit events like this wheels.component.ts
import { Component, EventEmitter } from '#angular/core';
import { CarService } from './car.service';
#Component({
selector: 'wheels',
template: '<a (click)="sendValues()"> Click me to send value </a>'
})
export class WheelsComponent {
constructor(private carService:CarService ){}
sendValues() {
/* Use service to emit events that can be used everywhere in the application */
this.carService.onLoaded.emit('Button in WheelsComponent was clicked ...');
};
}
and then capture this event from AppComponent for example app.component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { CarService } from './cars/car.service';
import { Subscription } from 'rxjs';
#Component({
selector: 'my-app',
templateUrl: `src/app.component.html`
})
export class AppComponent implements OnInit, OnDestroy{
private subscription: Subscription;
private loading = true;
name = 'Angular';
constructor(private carService: CarService){}
ngOnInit(){
this.subscription = this.carService.onLoaded.subscribe((message) => {
/*
Here you receive events from anywhere where
carService.onLoaded.emit() is used
**/
alert(`From AppComponent -> ${message}`);
});
}
ngOnDestroy(){
/* Don't forget to unsubscribe when component is destroyed */
this.subscription.unsubscribe();
}
}
I M P O R T A N T______________
If you want your service to work globally you need to declare it in the top level providers for example app.module.ts is a good place:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { CarComponent} from './cars/car.component';
import { WheelsComponent} from './cars/wheels.component';
import { HomeComponent} from './home.component';
import { routing } from './app.routing';
import { CarService } from './cars/car.service';
#NgModule({
imports: [ BrowserModule, FormsModule, routing ],
declarations: [ AppComponent, CarComponent, WheelsComponent, HomeComponent ],
providers: [ CarService ], // <-------- SEE HERE
bootstrap: [ AppComponent ]
})
export class AppModule { }
CLICK HERE TO SEE THE DEMO

How can I get a directive/component instance inside another component?

I have an AlertComponent that I would like to use as a directive in my AppComponent and expose it so that it's available (as a sort of singleton) to all the routes/children components from AppComponent. But I can't seem to find a way to get the instance of the AlertComponent object used as a directive in order to call it's methods and see the changes made on the directive (i.e. add/remove alerts to/from the page).
Here is AlertComponent:
import { Component } from 'angular2/core';
import { Alert } from './model';
#Component({
selector: 'alerts',
templateUrl: './alert/index.html'
})
export class AlertComponent {
alerts: Array<Alert>;
constructor() {}
add(alert: Alert) {
this.alerts.push(alert);
}
remove(index: number) {
this.alerts.splice(index, 1);
}
clear() {
this.alerts = [];
}
}
export { Alert };
And AppComponent:
import { Component, OnInit, provide } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import { HTTP_PROVIDERS, RequestOptions } from 'angular2/http';
import { CookieService } from 'angular2-cookie/core';
import { UserComponent } from '../user/component';
import { AlertComponent, Alert } from '../alert/component';
import { ExtendedRequestOptions } from '../extended/RequestOptions';
import { UtilObservable } from '../util/observable';
#Component({
selector: 'app',
template: `
<alerts></alerts>
<router-outlet></router-outlet>
`,
//styleUrls: [ 'app/style.css' ],
directives: [
ROUTER_DIRECTIVES,
AlertComponent
],
providers: [
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
provide(RequestOptions, { useClass: ExtendedRequestOptions }),
CookieService,
UtilObservable,
AlertComponent
]
})
#RouteConfig([{
path: '/user/:action',
name: 'User',
component: UserComponent,
useAsDefault: true
}
])
export class AppComponent implements OnInit {
constructor(public _alert: AlertComponent) {}
ngOnInit() {
this._alert.add(new Alert('success', 'Success!'));
}
}
I'd like to have the same instance of AlertComponent available to all descendant routes/children of AppComponent (e.g. UserComponent), so as to add alerts to the same directive.
Is this possible? Or is there another, more proper way to do this?
[Update]
The chosen solution answers the title question, but I also wanted to have a simple solution to share alerts among my components. Here's how to do that:
AlertComponent:
import { Component } from 'angular2/core';
import { Alert } from './model';
export class Alerts extends Array<Alert> {}
#Component({
selector: 'alerts',
templateUrl: './alert/index.html'
})
export class AlertComponent {
constructor(public alerts: Alerts) {}
add(alert: Alert) {
this.alerts.push(alert);
}
remove(index: number) {
this.alerts.splice(index, 1);
}
clear() {
this.alerts.length = 0;
}
}
export { Alert };
AppComponent:
import { Component, provide } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import { HTTP_PROVIDERS, RequestOptions } from 'angular2/http';
import { AlertComponent, Alerts } from '../alert/component'
import { UserComponent } from '../user/component';
import { ExtendedRequestOptions } from '../helpers/extensions';
#Component({
selector: 'app',
template: `<router-outlet></router-outlet>`,
directives: [
ROUTER_DIRECTIVES
],
viewProviders: [
provide(Alerts, { useValue: [] })
],
providers: [
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
provide(RequestOptions, { useClass: ExtendedRequestOptions })
]
})
#RouteConfig([{
path: '/user/:action',
name: 'User',
component: UserComponent,
useAsDefault: true
}
])
export class AppComponent {}
Basically, I'm providing a singleton array of alerts that's used by every AlertComponent.
You can move the provide() to providers (instead of viewProviders) if you want to use it outside of directives, but if not, keep it simple and restrict it this way.
Hope this helps someone :)
You need to use ViewChild decorator to reference it:
#Component({
})
export class AppComponent implements OnInit {
#ViewChild(AlertComponent)
_alert: AlertComponent;
ngAfterViewInit() {
// Use _alert
this._alert.add(new Alert('success', 'Success!'));
}
}
#ViewChild is set before the ngAfterViewInit hook method is called.
expose it so that it's available (as a sort of singleton) to all the
routes/children components from AppComponent.
Or is there another, more proper way to do this?
Create and bootstrap a service for AlertComponent, like this
AlertService
import {Injectable} from '#angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';
#Injectable()
export class AlertService {
private _alerts: Array<Alert> = [];
public alertsChange: Subject<Array<Alert>> = new Subject();
public get alerts(): Array<Alert> {
return this._alerts;
}
add(alert: Alert) {
this._alerts.push(alert);
this.alertsChange.next(this._alerts);
}
remove(index: number) {
this._alerts.splice(index, 1);
this.alertsChange.next(this._alerts);
}
clear() {
this._alerts = [];
this.alertsChange.next(this._alerts);
}
}
Bootstrap AlertService
import {bootstrap} from '#angular/platform-browser-dynamic';
import {YourApp} from 'path/to/YourApp-Component';
import { AlertService} from 'path/to/alert-service';
bootstrap(YourApp, [AlertService]);
AlertComponent
import { Component } from 'angular2/core';
import { Alert } from './model';
import { AlertService} from 'path/to/alert-service';
#Component({
selector: 'alerts',
templateUrl: './alert/index.html'
})
export class AlertComponent {
alerts: Array<Alert>;
constructor(alertService: AlertService) {
alertService.alertsChange.subscribe((moreAlerts: Array<Alert>) => {
this.alerts = moreAlerts;
})
}
}
All the routes/children components
(sample):
import { Component} from '#angular/core';
import { AlertService} from 'path/to/alert-service';
#Component({
template: `.....`
})
export class SampleComponent {
constructor(public alerts: AlertService){}
ngOnInit(){
this.alerts.add(new Alert('success', 'Success!'));
}
ngOnDestroy(){
this.alerts.clear();
}
}
To see other alike examples see this question

Categories

Resources