I started learning Angular 4 and got to the part with HTTP Client. Right now I'm trying to make an http call from the component (yes, I know I should transfer it to service, but still)
But for some reason, when I try to inject HttpClient into my Component I get the next error:
Uncaught Error: Can't resolve all parameters for PromocodeComponent:
(?).
Here's the code of my component:
import { Ticket } from '../../classes/Ticket.class'
import { Component, Input } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'promocode',
templateUrl: './promocode.template.html',
styleUrls: ['./promocode.styles.scss']
})
export class PromocodeComponent {
#Input() ticket: Ticket;
state: String = "normal";
promocode: String = "";
constructor(private http: HttpClient) {}
promocodeValidate(event): void{
console.log(this.promocode);
console.log(event);
this.http.get('/promocode/asdasda').subscribe(data => {
console.log(data);
});
}
}
And my app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { MovieBadgeComponent } from './movie-badge/movie-badge.component';
import { TicketComponent } from './ticket/ticket.component';
import { PromocodeComponent} from './promocode/promocode.component';
import { FormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
MovieBadgeComponent,
TicketComponent,
PromocodeComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
It turned out, for me, that I forgot the #Injectable decorator on my service. In earlier angular (>=2), i remember the #Injectable as being optional... Guess not anymore?
Turns out, I missed
"emitDecoratorMetadata": true
in tsconfig
fml...
I got the same error when I ran unit testing (a spec.ts file) with Angular.
The following is what I did:
import { HttpClientModule, HttpClient } from '#angular/common/http';
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ],
imports: [
HttpClientModule
],
schemas: [NO_ERRORS_SCHEMA],
providers: [
HttpClient,
]
})
.compileComponents();
}));
and the error was gone.
Related
I am using JSONPlaceholder to get data in service, but I am unable to get data at all. Please, help me out.
user.component.html
<p (click)="getUsers()">Click Me!</p>
<ul *ngFor="let x of users">
<li>{{x.name}}, {{x.age}}</li>
</ul>
user.component.ts
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService } from '../../services/data.service';
import { Http } from '#angular/http';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private http:Http) { }
ngOnInit() {
}
getUsers(){
console.log(this.http.get("https://jsonplaceholder.typicode.com/posts"));
}
}
app.module.ts
//Basic File Inclusions
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
//Additional files inclusion
import { AppComponent } from './app.component';
import { UserComponent } from './components/user/user.component';
import { DataService } from './services/data.service';
import { Http } from '#angular/http';
#NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule
],
providers: [ Http ],
bootstrap: [AppComponent]
})
export class AppModule { }
Please, can someone help me out making a successfull service call via http and get data on console.
Import
import { HttpModule } from '#angular/http';
in app.module.ts
imports: [HttpModule]
Rest of code will be same as you posted.
calling http like
this.http.get(`https://jsonplaceholder.typicode.com/posts`).subscribe(
data => {
console.log(data)
});
user.component.ts
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService } from '../../services/data.service';
import { Http } from '#angular/http';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit() {
}
this.http.get(`https://jsonplaceholder.typicode.com/posts`).subscribe(
data => {
console.log(data)
});
}
app.module.ts
//Basic File Inclusions
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
//Additional files inclusion
import { AppComponent } from './app.component';
import { UserComponent } from './components/user/user.component';
import { DataService } from './services/data.service';
import { Http } from '#angular/http';
import { HttpModule } from "#angular/http";
#NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule,
HttpModule
],
providers: [ Http ],
bootstrap: [AppComponent]
})
export class AppModule { }
Hope this may help you..
You are just calling http.get(url) and expecting something in return is like calling ajax method without success and error callback methods.
Kindly check Http documentation and usage of get and post methods
Mistake/Wrong Assumptions:
this.http.get(https://jsonplaceholder.typicode.com/posts) will not return http response which are expecting
Reality/Correct Approach:
You can use either pipe(can be used in the service) or subscribe(can be used in Component) method on http's get method whose return type is Observable.
Based on your requirement, you can use either of them
http.get('https://jsonplaceholder.typicode.com/posts')
// Call map on the response observable to get the parsed people object
.pipe(map(res => res.json()))
// Subscribe to the observable to get the parsed people object and attach it to the
// component
.subscribe(posts => this.posts = posts)
Hence your component code becomes:
user.component.ts
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService } from '../../services/data.service';
import { Http } from '#angular/http';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private http:Http) { }
ngOnInit() {
}
getUsers(){
this.http.get("https://jsonplaceholder.typicode.com/posts")
.subscribe(posts=> console.log(posts))
}
}
I am facing the problem in angular 4.4 , In my app, I have hierarchical view. In which I have created a
:= module 1 -> module 2 -> my component.
I have declared everything correctly. , But still I'm getting error.
Declared component.
Imported it into other module.
selector name is same.
Exported component in module 2.
Imported module 2 in module 1.
What could be the catch?
Component Code:
Admin -> Configuration -> mycomponent
//My component
import { Component, OnInit, ViewChild, ChangeDetectorRef } from '#angular/core';
#Component({
selector: 'test-mycomponent',
templateUrl: './mycomponent.component.html',
styleUrls: ['./mycomponent.component.scss']
})
export class MyComponentComponent implements OnInit {
#ViewChild('myComponentTable')
constructor() {
}
ngOnInit() {
//init functionality
}
}
// configure module code
import { NgModule,Component } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { MyComponentComponent } from './mycomponent/mycomponent.component';
#NgModule({
imports: [
CommonModule,
WidgetsModule,
FormsModule,
NgbModule
],
declarations: [
MyComponent
],
providers: [
],
exports: [
MyComponent
]
})
export class ConfigurationModule { }
//Main module admin
import { NgModule, Component } from '#angular/core';
import { CommonModule } from '#angular/common';
import { ConfigurationModule } from './configuration/configuration.module';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { MyComponentComponent } from './configuration/mycomponent/mycomponent.component';
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
CommonModule,
NgbModule,
FormsModule,
ConfigurationModule
],
declarations: [
],
exports: [
]
})
export class AdminModule { }
and I am calling that template in another file
//Test file html
<ng-template>
<test-mycomponent></test-mycomponent>
</ng-template>
You are not declaring the right component the name should be MyComponentComponent in the declerations and exports:
import { MyComponentComponent } from './mycomponent/mycomponent.component';
declarations: [
MyComponent //should be MyComponentComponent
],
providers: [
],
exports: [
MyComponent //should be MyComponentComponent
]
New to Angular, please bear with me. I need to load in tweets from a specific timeline. What is the best way to accomplish this? I've tried using this package (https://www.npmjs.com/package/ng4-twitter-timeline), and have followed the instructions in that documentation, but I still get the error that "ng4-twitter-timeline is not a known element."
I've also tried adding in
<script src="https://platform.twitter.com/widgets.js" async></script>
to index.html...
Are there additional scripts that need to be loaded in for this to work?
app.module.ts
...
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { RouterModule } from '#angular/router';
import { SwiperModule } from 'angular2-useful-swiper';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { ShareModule } from 'ng2share/share.module';
import { MasonryModule } from 'angular2-masonry';
import { routes } from './app-routing.module';
import { Ng4TwitterTimelineModule } from 'ng4-twitter-timeline/lib/index';
#NgModule({
declarations: [
...
],
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
AngularFontAwesomeModule,
SwiperModule,
RouterModule.forRoot(routes),
ShareModule,
MasonryModule,
Ng4TwitterTimelineModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
tweets.component.ts
import { Component, OnInit } from '#angular/core';
import { Ng4TwitterTimelineService } from 'ng4-twitter-timeline/lib/index';
#Component({
selector: 'app-tweets',
templateUrl: './tweets.component.html',
styleUrls: ['./tweets.component.scss']
})
export class TweetsComponent implements OnInit {
constructor(private ng4TwitterTimelineService: Ng4TwitterTimelineService) {}
ngOnInit() {}
}
tweets.component.html
<ng4-twitter-timeline [dataSrc]="{sourceType: 'profile',screenName: 'lokers_one'}" [opts]="{tweetLimit: 2}"></ng4-twitter-timeline>
You should add .forRoot when you imports Ng4TwitterTimelineModule in #ngModule. So your app.module.ts should look like that:
...
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { RouterModule } from '#angular/router';
import { SwiperModule } from 'angular2-useful-swiper';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { ShareModule } from 'ng2share/share.module';
import { MasonryModule } from 'angular2-masonry';
import { routes } from './app-routing.module';
import { Ng4TwitterTimelineModule } from 'ng4-twitter-timeline/lib/index';
#NgModule({
declarations: [
...
],
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
AngularFontAwesomeModule,
SwiperModule,
RouterModule.forRoot(routes),
ShareModule,
MasonryModule,
Ng4TwitterTimelineModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Figured it out, everyone. The account used in the demo has protected tweets... which is why nothing was embedding... I changed the account and it does work. But still don't understand why I'm still getting this error: 'ng4-twitter-timeline' is not a known element'
I am new on angular 2. I was following the legacy quick-start application, Tour of Heroes.
I created services as mentioned in the application.
I have a service HeroService. Which is used to pull all the heroes data.
I have included the HeroService at the app.module file as provider to be able to access it through out the application for all application.
My app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroesComponent } from './heroes.component';
import { HeroService } from './hero.service';
#NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{
path: 'heroes',
component: HeroesComponent
}
])
],
declarations: [ AppComponent, HeroesComponent, HeroDetailComponent ],
providers: [ HeroService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
And my Component File where I want to Access the HeroService to get data is:
export class HeroesComponent implements OnInit {
constructor(private heroService: HeroService) { }
}
The problem is I am getting an error like this, when i build the project :
Cannot find name 'HeroService'.
I have followed all the steps correctly. If I import the HeroService in my HeroesComponent, it seems to work. But fails when not imported.
Am I missing some step. As far as I understood declaring the provider on app.module will register it to use throughout the application/components without need of importing it each time.
Please correct me If I am wrong somewhere.
You need to import inside the component as well
import { HeroService } from './hero.service';
I am trying to use angulartics2 with my application.
I have configured correctly as it mentioned in the document.
Note: There is no place it is mentioned to add the provider as a dependency..
When i try to run the application, it shows the error as below.
EXCEPTION: No provider for Angulartics2GoogleAnalytics! Error: DI
Error
at NoProviderError.ZoneAwareError (zone.js:811)
at NoProviderError.BaseError [as constructor] (core.umd.js:1186)
at NoProviderError.AbstractProviderError [as constructor] (core.umd.js:1371)
at new NoProviderError (core.umd.js:1411)
at ReflectiveInjector_.throwOrNull (core.umd.js:3394)
at ReflectiveInjector.getByKeyDefault (core.umd.js:3433)
at ReflectiveInjector.getByKey (core.umd.js:3380)
at ReflectiveInjector.get (core.umd.js:3140)
at AppModuleInjector.NgModuleInjector.get (core.umd.js:8996)
at CompiledTemplate.proxyViewClass.AppView.injectorGet (core.umd.js:12465)
at CompiledTemplate.proxyViewClass.DebugAppView.injectorGet (core.umd.js:12845)
at CompiledTemplate.proxyViewClass.View_AppComponent_Host0.createInternal
(/AppModule/AppComponent/host.ngfactory.js:15)
at CompiledTemplate.proxyViewClass.AppView.createHostView (core.umd.js:12421)
at CompiledTemplate.proxyViewClass.DebugAppView.createHostView (core.umd.js:12829)
at ComponentFactory.create (core.umd.js:7766) 1: https://github.com/angulartics/angulartics2
App.component.ts
import { Component } from '#angular/core';
import { Angulartics2GoogleAnalytics } from 'angulartics2';
#Component({
selector: 'my-app',
moduleId: module.id,
templateUrl: `./app.component.html`,
styleUrls: ['/app.componenet.css']
})
export class AppComponent {
title = 'Angular2 google analytics';
constructor(angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics) {}
}
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { HttpModule } from '#angular/http';
import { FormsModule } from '#angular/forms';
import { Angulartics2Module, Angulartics2GoogleAnalytics } from 'angulartics2';
#NgModule({
imports: [ HttpModule, BrowserModule, FormsModule, Angulartics2Module.forRoot([ Angulartics2GoogleAnalytics ])],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
})
export class AppModule { }
use providers to initiate your providers in component.
#Component({
selector: 'yourselector',
styleUrls: [''],
templateUrl: '',
providers: [Angulartics2GoogleAnalytics]
})
Try this.
Your problem should reside in your constructor:
constructor(angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics) {}
you should add e.g public in front of your provider:
constructor(public angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics) {}