so i am trying to retrieve data from Api and cant retrieve with key selection
app/app.component.ts
import {Component} from 'angular2/core';
import {Http} from 'angular2/http';
import {httpServiceClass} from './service';
import {HTTP_PROVIDERS} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Api} from './api';
#Component({
selector: 'my-app',
templateUrl: 'mytemplate.html',
providers:[httpServiceClass,HTTP_PROVIDERS]
})
export class AppComponent implements OnInit{
private api:Api[];
constructor(private getservice:httpServiceClass){
}
ngOnInit(){
this.getservice.httprequest()
.subscribe(data => this.api = data );
}
}
service file
app/app.service.ts
import {Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
import {Api} from './api';
#Injectable()
export class httpServiceClass{
constructor(private http: Http){}
httprequest(): Observable<Api[]>{
return this.http.get(' http://date.jsontest.com')
.map(response => response.json());
}
}
api.ts
export interface Api{
time:string;
date:string;
}
mytemplate.html
<h1 >HTTP : {{api|json}}</h1>
returns HTTP : { "time": "01:52:41 PM", "milliseconds_since_epoch": 1472910761126, "date": "09-03-2016" }
i tried selecting by key
<h1 >HTTP : {{api.time}}</h1>
returns in console
EXCEPTION: Cannot find a differ supporting object '[object Object]' in [api in AppComponent#0:4]
An interface in runtime is nothing in javascript world. Try changing your interface to class and see if it fixes the problem. Then refractor the code accordingly.
Related
This is my first contact with AngularJS. I would like to integrate the api with a front in Angular, my goal is just to return a list of data, making it as simple as possible is my goal.
[link][1] Setup for server communication
Before you can use HttpClient, you need to import the Angular HttpClientModule. Most apps do so in the root AppModule.
app/app.module.ts (excerpt)
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
You can then inject the HttpClient service as a dependency of an application class, as shown in the following ConfigService example.
app/config/config.service.ts (excerpt)
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}
The HttpClient service makes use of observables for all transactions. You must import the RxJS observable and operator symbols that appear in the example snippets. These ConfigService imports are typical.
app/config/config.service.ts (RxJS imports)
content_copy
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
im developing an admin panel where the admin can see all the bookings that have been requested and select those who he will accept; and I want to display those 'accepted' bookings in a different tab (different component, in a different route). Im using a SharedService with a BehaviorSubject but it doesnt work: All I get in the 2nd component is an anonymousSubject array, which is empty. Im not showing the first component which sends the booking to the service cause thats working fine.
Help please!
shared Service
import {Injectable} from '#angular/core';
import {BehaviorSubject} from 'rxjs';
import {Turno} from '../models/turno';
#Injectable({
providedIn: 'root',
})
export class SharedService{
private acceptedBookings=[];
public acceptedBookingsSubject= new BehaviorSubject<Turno[]>([]);
//public turno:Turno;
constructor(){
}
addToAccepted(turno : Turno){
this.acceptedBookings.push(turno);
this.acceptedBookingsSubject.next(this.acceptedBookings);
console.log(this.acceptedBookingsSubject);
}
}
and here is the second component.
Second component, which consumes the service and has to display the array.
import { Component, OnInit} from '#angular/core';
import {SharedService} from '../../services/shared.service';
import {Observable} from 'rxjs';
import {Turno} from '../../models/turno';
import {share} from 'rxjs/operators';
#Component({
selector: 'app-turnoaceptado',
templateUrl: './turnoaceptado.component.html',
styleUrls: ['./turnoaceptado.component.css'],
providers:[SharedService]
})
export class TurnoaceptadoComponent implements OnInit {
public acceptedBookings:Observable<Turno[]>;
ngOnInit(): void {
}
constructor(private _sharedService: SharedService) {
this._sharedService.acceptedBookingsSubject.pipe(share());
}
}
And in the html of the 2nd component im using the async pipe |
At ngOnInit, just add:
this.acceptedBookings = this._sharedService.acceptedBookingsSubject.asObservable();
Then you can choose if you prefer to create a subscription on it or use pipe async.
Additional tip, once you set the SharedService with { providedIn: 'root' }, you don't need to put the SharedService on any providers array.
I have created a demo: stackblitz
event-component.ts
EventService is the service class Injectable but i have getting error [ts] cannot find module '/shared/event.service' but app.module.ts i was giving same path of this service it is working their. path is correct please tell me whats wrong in this..
import { Component } from '#angular/core'
import { EventService } from '/shared/event.service'
//[ts] Cannot find module '/shared/event.service'.
#Component({
selector: 'event-list',
template: `<div><h2>we are using Angular Js 2</h2><hr/>
<div class="row">
<div class="col-md-6" *ngFor="let event of events">
<event-thumbnil [eventList] = "event" >
</event-thumbnil>
</div>
</div>
</div>`
})
export class EventsListComponent {
events:any[]
constructor(private eventService : EventService)
{
this.events= this.eventService.getEvents();
}
}
app.module.ts
import { NgModule } from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
import {EventsAppComponent } from './events-app.component'
import { EventsListComponent } from './Events/events-list.component'
import {EventThumbnilComponent } from './Events/events-list.thumbnil'
import {NavabarComponent} from './nav/navbar-component'
import {EventService} from './shared/event.service'
#NgModule({
imports:[BrowserModule],
declarations: [EventsAppComponent, EventsListComponent,EventThumbnilComponent,NavabarComponent],
bootstrap:[EventsAppComponent],
providers:[EventService]
})
export class AppModule{
}
in your typescript file you forget to give the directory for you service
import {EventService} from '../shared/event.service'
check it out it may works
In my main.ts the code is like this.
import {provide, enableProdMode} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';
import {APP_BASE_HREF} from 'angular2/platform/common';
import {AppComponent} from './app/components/app.component';
enableProdMode();
bootstrap(AppComponent, [
ROUTER_PROVIDERS, HTTP_PROVIDERS,
provide(APP_BASE_HREF, { useValue: '<%= APP_BASE %>' })
]);
In my app.component.ts file I have the follwing code.
import {Component} from 'angular2/core';
import {enableProdMode} from 'angular2/core';
import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams} from 'angular2/router';
import {SportsLiveFeedService} from '../shared/index';
import {MainComponent} from '../main/index';
import {ResultsComponent} from '../results/index';
#Component({
selector: 'sd-app',
viewProviders: [SportsLiveFeedService],
templateUrl: 'app/components/app.component.html',
styleUrls: ['css/bootstrap.min.css', 'css/main.css'],
directives: [ROUTER_DIRECTIVES]
})
#RouteConfig([
{
path: '/',
name: 'Main',
component: MainComponent
},
{
path: '/results/:id',
name: 'Results',
component: ResultsComponent
}
])
export class AppComponent {
constructor(private router: Router) {}
}
And in the ResultsComponent my code is like this.
import {Component} from 'angular2/core';
import {Inject} from 'angular2/di';
import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/common';
import {SportsLiveFeedService} from '../../shared/index';
#Component({
selector: 'sd-about',
templateUrl: 'app/results/components/results.component.html',
styleUrls: ['css/bootstrap.min.css', 'css/main.css'],
directives: [FORM_DIRECTIVES, CORE_DIRECTIVES],
providers: [SportsLiveFeedService]
})
export class ResultsComponent implements OnInit {
eventsDetails: [];
constructor(private _sportsLiveFeedService: SportsLiveFeedService){
this._sportsLiveFeedService = _sportsLiveFeedService;
}
ngOnInit(){
this._sportsLiveFeedService
.getEachEventInDetailByMeetingId()
.subscribe(p => this.eventsDetails = p)
}
}
The issue is when I first screen is loading just fine. But when I navigate to http://localhost:5555/results/121212 like this, The second screen UI is not showing. Please help me to fix this issue. I am new to Angular 2.0
I'm currently receiving the following error:
EXCEPTION: No provider for Http! (Login -> AuthHttp -> Http)
AuthHttp is a reference to Angular2-jwt. Could this be an issue with that? I've been staring at this for a while, and I can't find what error I could possibly have.
In my login.ts:
import {Component} from 'angular2/core';
import {
FORM_DIRECTIVES,
FormBuilder,
ControlGroup,
Validators,
AbstractControl,
Control
} from 'angular2/common';
import {Http, Headers} from 'angular2/http';
import {Router} from 'angular2/router';
import {ButtonRadio} from 'ng2-bootstrap/ng2-bootstrap';
import {AuthHttp, AuthConfig} from 'angular2-jwt';
import {AuthService} from '../../services/auth/authService';
import {AlertService} from '../../services/alerts/alertsService';
import {User} from '../../datatypes/user/user';
#Component({
selector: 'login',
template: require('./login.html'),
directives: [ ButtonRadio, FORM_DIRECTIVES ],
providers: [AuthService, AlertService, Http, AuthHttp]
})
In my main.ts:
document.addEventListener('DOMContentLoaded', function main() {
bootstrap(App, [
('production' === process.env.ENV ? [] : ELEMENT_PROBE_PROVIDERS),
HTTP_PROVIDERS,
ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy }),
provide(AuthConfig, { useFactory: () => {
return new AuthConfig({
headerName: 'Authorization',
//headerPrefix: 'Bearer ',
tokenName: 'auth_token',
noJwtError: true
});
}}),
AuthHttp,
Http,
ConnectionBackend
])
.catch(err => console.error(err));
});
You have to add HTTP_BINDINGS
import {HTTP_BINDINGS} from 'angular2/http';
bootstrap(..., [
...
HTTP_BINDINGS,
...
]).catch(...);
It seems that this was indeed an error with Angular2-jwt, or at least with its configuration. Here is the way it should be configured.
Still, I've managed to clean things up a bit. If this problem actually runs deeper, I'll try to reopen.