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.
Related
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
I am new to Angular nativescript, I created a service using the "ng generate service" command in my native angular application, but when importing the service I get the error that the module cannot be found
app.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptModule, NativeScriptHttpClientModule } from "#nativescript/angular";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { LoginComponent } from './components/login/login.component';
#NgModule({
bootstrap: [
AppComponent
],
imports: [
NativeScriptModule,
AppRoutingModule,
NativeScriptHttpClientModule
],
declarations: [
AppComponent,
LoginComponent,
],
providers: [],
schemas: [
NO_ERRORS_SCHEMA
]
})
/*
Pass your application module to the bootstrapModule function located in main.ts to start your app
*/
export class AppModule { }
ApiBackRequestService.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { environment } from '../environments/environment';
#Injectable({
providedIn: 'root'
})
export class ApiBackRequestService {
constructor(
private http: HttpClient) {
}
}
Login.component.ts
import { Component, OnInit } from '#angular/core';
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
#Component({
selector: 'ns-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
pokemon = [];
constructor(private api: ApiBackRequestService) { }
ngOnInit(): void {
}
}
Thanks
Is it a code-sharing project? in the Login.component.ts file just add # before the src.
change
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
to
import { ApiBackRequestService } from '#src/app/services/api-back-request.service';
this solved my problem
import { ApiBackRequestService } from '../../services/api-back-request.service';
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.
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?
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.