Error: Unreachable code detected ionic 3 weather app - javascript

Ok, so I am following along the traversy media tutorial on ionic 3, and when i get to the part where you create a provider I get and error that says unreachable code detected in here:
.map((res: Response) => res.json() );
and it also says on typescript
cannot find the name 'map' did you mean 'Map'?
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
#Injectable()
export class WeatherProvider {
apiKey = "89cca14f4ffcd27d602ad5e587f8e17f";
url;
constructor(public http: HttpClient) {
console.log('Hello WeatherProvider Provider');
this.url = "api.openweathermap.org/data/2.5/weather?q=";
}
getWeather(city, country){
return this.http.get(this.url+city+','+country);
.map((res: Response) => res.json() );
}
}

The return statement in getWeather() is making the .map() unreachable. You should make the return statement the last statement in the function.

Related

error TS2339: Property 'map' does not exist on type 'Observable<Response>'

I am trying to get data from mongodb, for which I have written a service. But I am getting an error like error TS2339: Property 'map' does not exist on type 'Observable<Response>'
Please help me to resolve this error...
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class DataService {
result:any;
constructor(private _http: Http) { }
getUsers() {
return this._http.get("/api/users")
.map(result => this.result = result.json().data);
}
}
You have to import and use the map operator differently:
Change
import 'rxjs/add/operator/map';
to
import { map } from 'rxjs/operators';
Then, do
return this._http.get("/api/users")
.pipe(map(result => this.result = result.json().data));
Addiontal suggestion from Vikas
Migrate from the Http service to the HttpClient. see migration guide
To update to HttpClient, you’ll need to replace HttpModule with
HttpClientModule from #angular/common/http in each of your modules,
inject the HttpClient service, and remove any map(res => res.json())
calls, which are no longer needed.

Angular - TS - Error TS1109: Expression Expected

I am new to Angular and trying one of the tutorial from 'Traversy Media' on YouYube.
I am trying to create a user component and then fetch posts from a link, but when I am running the code it is giving me Error TS1109: Expression Expected
ERROR
src/app/services/posts.service.ts(12,13): error TS1109: Expression expected.
CODE that I am using
import {Injectable} from '#angular/core';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class PostsService{
constructor(private http: Http){
console.log('PostsService Initialized...');
}
getPosts(){
return.this.http.get('https://jsonplaceholder.typicode.com/posts')
.map(res => res.json());
}
}
Please do forgive me if I have done a blunder as I am new to this technology.
Remove the . after return
getPosts(){
return this.http.get('https://jsonplaceholder.typicode.com/posts')
.map(res => res.json());
}
This part: return.this needs to have a space and not a dot: return this

Angular 2 - [Object Object] - Access the property of the object using dot notation does not work

I know in Angular there are two ways to access object values
Access the property of the object using dot notation (obj.property).
Access the property of the object by passing in key value for example obj["property"]
If I output {{ page | json }} , I get an object with all the list.
If I do ' page.id ' or any property I get an error:
EXCEPTION: Uncaught (in promise): Error: Error in ./PageSingleComponent class PageSingleComponent - inline template:3:6 caused by:
undefined is not an object (evaluating 'self.context.page.id')
My component is
import { Component, OnInit } from '#angular/core';
import { Page } from '../page';
import { PageService } from '../page.service';
import { Router, ActivatedRoute, Params } from '#angular/router';
#Component({
selector: 'app-page-single',
templateUrl: './page-single.component.html',
styleUrls: ['./page-single.component.css'],
providers: [PageService]
})
export class PageSingleComponent implements OnInit {
page: Page;
constructor( private pageService: PageService, private route: ActivatedRoute ) { }
getPost(slug){
console.log('page slug is',slug);
this.pageService
.getPost('other-page')
.subscribe(res => {
this.page = res[0];
console.log('posts inside', res, slug);
});
}
ngOnInit() {
this.route.params.forEach((params: Params) => {
let pageSlug = params['pageSlug'];
this.getPost(pageSlug)
});
}
}
Page service
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Page } from './page';
#Injectable()
export class PageService {
private _wpBase = "http://ecommerce-ux.london/wp-json/wp/v2/";
constructor(private http: Http) {
this.http = http
this.getPost().subscribe(
(data) => {
console.log('posts', data)
},
(err) => console.log("Error Loging In:",err),
() => { console.log("All Good With The posts Data") }
);
}
getPages(): Observable<Page[]> {
return this.http
.get(this._wpBase + 'pages')
.map((res: Response) => res.json());
}
getPost(pageSlug): Observable<Page> {
return this.http
.get(this._wpBase + `pages?slug=${pageSlug}`)
.map((res: Response) => res.json());
}
}
Page-single.component.html
<div>
<!-- {{ page | json }} works -->
<h1>{{ page.id }}</h1>
</div>
Console.log
Because the page property of your component is not assigned a default value it’s not actually defined until the subscribe callback in PageSingleComponent.getPost sets it. This causes an error because you can’t access the id property of undefined since it's not an object.
To fix this you need to avoid evaluating the template expression until page has been set. You can do this via ng-if:
<h1 *ngIf=“page”>{{ page.id }}</h1>
Or you can use the safe navigation operator:
<h1>{{ page?.id }}</h1>

Ionic2, Angular2, HTTP and Observables

After reading almost everything I found about observables, I still don't understand pretty well how they work.
I am doing the http request here:
import { Component, OnInit, Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
webs: any;
getWebs(): any{
return this.http.get( 'here the url' )
.map((res: Response) => res.json());
}
constructor(public navCtrl: NavController, private http: Http) {}
ngOnInit(){
this.getWebs().subscribe(response => {
this.webs = response;
console.log(this.webs);
});
}
}
On the console, this.webs is correctly printed. That means, the get request ist working fine and I am retrieving the object I want. That is a normal JSON object.
The problem is, on the view, if I try to print some property of the object (the same properties I see on the console) like that
{{ webs.name }}
I get the whole time that error:
Error in ./HomePage class HomePage - caused by: Cannot read property 'name' of undefined
That was sooo easy with Angular 1 :( I already read a lot of tutorials but I can't find any answer to my problem.
Thanks for your help.
The view is shown before the http response is returned.
{{webs?.name}}
should work.
Or do this.webs=getWebs()
and {{webs.name | async}}
It should be something
this.getWebs().then((webs) => {
webs.subscribe(response => {
this.webs = response;
resolve(webs);
console.log(this.webs);
});
})
so after you getWebs do this.This is untested code but you get the logic.
You are calling before you get data.
ngOnInit(){
return new Promise(resolve => {
this.http.get('webs.json')
.map(res => res.json())
.subscribe(webs => {
this.webs = webs;
resolve(this.webs);
});
});
}

Accessing a service in #CanActivate hook

I can't figure out a way to access a service and properly configure it's dependencies when that service is accessed from Angular's #CanActivate hook.
Before I instantiate a component I need to first check that the user is authenticated. My hook looks like:
import {AuthenticationService} from '../authentication/authentication.service';
.................
#CanActivate((next, prev) => {
var injector = Injector.resolveAndCreate([
AuthenticationService
])
var authService = injector.get(AuthenticationService);
return authService.getUser();
})
export class ShellComponent { }
The error I get is EXCEPTION: No provider for Http! (AuthenticationService -> Http). It should be noted that HTTP_PROVIDERS are injected when the application is bootstrapped.
My authentication service is the following:
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
#Injectable()
export class AuthenticationService {
constructor(private _http:Http) {}
getUser() {
var resolver = function(resolve, reject) {
setTimeout(function doneCounting() {
resolve(true);
}, 5000);
}
return new Promise<Boolean>(resolver);
}
}
Any help or insight would be appreciated.
All you need is to add this dependencies to resolveAndCreate, so your code will will be:
var injector = Injector.resolveAndCreate([HTTP_PROVIDERS, AuthenticationService])

Categories

Resources