Api 无法读取未定义的角度2错误的get属性
嗨,我正试图从谷歌api获取城市名称,但下面的错误是我的代码 appcomponent类Api 无法读取未定义的角度2错误的get属性,api,google-maps-api-3,typescript,maps,angular,Api,Google Maps Api 3,Typescript,Maps,Angular,嗨,我正试图从谷歌api获取城市名称,但下面的错误是我的代码 appcomponent类 import {Component, OnInit} from 'angular2/core'; import {marketComponent} from './market.component'; import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router'; import {introComponent} fro
import {Component, OnInit} from 'angular2/core';
import {marketComponent} from './market.component';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {introComponent} from './intro.component';
import {geoService} from './service.geo';
import {JSONP_PROVIDERS} from 'angular2/http';
declare var google: any;
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
directives: [ROUTER_DIRECTIVES],
providers: [JSONP_PROVIDERS, geoService]
})
@RouteConfig([
{ path: '/intro', name: 'Intro', component: introComponent, useAsDefault: true },
{ path: '/market', name: 'Market', component: marketComponent },
])
export class AppComponent {
constructor(private _http: geoService) { }
public maps;
public cat_error: Boolean = false;
public xml_Latitude :string;
public xml_Lang: string;
ngOnInit() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
var input: any = document.getElementById('google_places_ac');
var autocomplete = new google.maps.places.Autocomplete(input, {});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
console.log(place)
});
}
showPosition(position) {
this.xml_Latitude = position.coords.latitude;
this.xml_Lang = position.coords.longitude;
this._http.getPlaces(this.xml_Latitude, this.xml_Lang).subscribe(
data => { this.maps = data },
err => { this.cat_error = true }
);
var result = this.maps.results;
var city = result[0].address_components[4].long_name + "," + result[0].address_components[6].long_name;
alert(city);
}
}
和地理服务文件
import {Injectable} from 'angular2/core';
import { Response, Jsonp} from 'angular2/http';
import 'rxjs/add/operator/map';
@Injectable()
export class geoService {
constructor(private http: Jsonp) { }
public xml_Latitude: string;
public xml_Lang: string;
public getPlaces(xml_Latitude, xml_Lang) {
return this.http.get(`http://maps.googleapis.com/maps/api/geocode/json?latlng=
'${this.xml_Latitude}','${this.xml_Lang}'&sensor=true`)
.map((res: Response) => res.json())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return error.json().error || 'Server error';
}
}
error还表示getplaces不是一个函数,我想我遗漏了一些东西,但不知道是什么…我认为应该将
结果
块移动到与getplaces方法调用关联的subscribe回调中:
showPosition(position) {
this.xml_Latitude = position.coords.latitude;
this.xml_Lang = position.coords.longitude;
this._http.getPlaces(this.xml_Latitude, this.xml_Lang).subscribe(
data => {
this.maps = data;
var result = this.maps.results; // <----------
var city = result[0].address_components[4].long_name + "," + result[0].address_components[6].long_name;
alert(city);
},
err => { this.cat_error = true }
);
}
我认为应该将
result
块移动到与getPlaces方法调用关联的subscribe回调中:
showPosition(position) {
this.xml_Latitude = position.coords.latitude;
this.xml_Lang = position.coords.longitude;
this._http.getPlaces(this.xml_Latitude, this.xml_Lang).subscribe(
data => {
this.maps = data;
var result = this.maps.results; // <----------
var city = result[0].address_components[4].long_name + "," + result[0].address_components[6].long_name;
alert(city);
},
err => { this.cat_error = true }
);
}
除了Thierry确定的回调顺序问题之外,您在这一行上还有一个丢失的
this
上下文:
navigator.geolocation.getCurrentPosition(this.showPosition);
问题
您有一个典型的JavaScript问题,称为不正确的this
context。
与其他语言(如C#和Java)中的行为不同
这个
的工作原理
函数中的此
关键字确定如下:
*如果函数是通过调用.bind
创建的,则此
值是提供给绑定的参数
*如果函数是通过方法调用调用的,例如expr.func(args)
,则此
为expr
*否则
*如果代码在中,此
为未定义
*否则,此
为窗口
(在浏览器中)
让我们看看这在实践中是如何工作的:
class Foo {
value = 10;
doSomething() {
// Prints 'undefined', not '10'
console.log(this.value);
}
}
let f = new Foo();
window.setTimeout(f.doSomething, 100);
此代码将打印未定义的
(或在严格模式下引发异常)。
这是因为我们最终进入了上面决策树的最后一个分支。
调用了doSomething
函数,该函数不是bind
调用的结果,也不是在方法语法位置调用的
我们无法查看setTimeout
的代码来查看它的调用,但我们不需要这样做。
需要了解的是,所有的doSomething
方法都指向同一个函数对象。
换言之:
let f1 = new Foo();
let f2 = new Foo();
// 'true'
console.log(f1.doSomething === f2.doSomething);
我们知道,setTimeout
只能看到我们传递给它的函数,所以当它调用该函数时,
它无法知道该提供哪个。
此
上下文已丢失,因为我们在未调用方法的情况下引用了该方法
红旗
一旦您了解了这个问题,就很容易发现它们:
class Foo {
value = 10;
method1() {
doSomething(this.method2); // DANGER, method reference without invocation
}
method2() {
console.log(this.value);
}
}
解决方案
这里有几个选项,每个选项都有自己的权衡。
最佳选择取决于从不同的调用站点调用该方法的频率
类定义中的Arrow函数
不要使用常规方法语法,而是使用初始化每个实例成员
class DemonstrateScopingProblems {
private status = "blah";
public run = () => {
// OK
console.log(this.status);
}
}
let d = new DemonstrateScopingProblems();
window.setTimeout(d.run); // OK
- 好/坏:这会为类的每个实例的每个方法创建一个额外的闭包。如果这个方法通常只在常规方法调用中使用,那就太过分了。但是,如果在回调位置大量使用它,则类实例捕获
此
上下文比每个调用站点在调用时创建新的闭包更有效
- 好:外部调用方不可能忘记处理此上下文
- 好:TypeScript中的Typesafe
- 好:如果函数有参数,则无需额外工作
- 错误:派生类无法调用使用
super以这种方式编写的基类方法。
- 坏:哪些方法是“预绑定”的,哪些方法不会在类及其使用者之间创建额外的非类型安全契约的确切语义
参考点的函数表达式
出于解释原因,此处显示了一些虚拟参数:
class DemonstrateScopingProblems {
private status = "blah";
public something() {
console.log(this.status);
}
public run(x: any, y: any) {
// OK
console.log(this.status + ': ' + x + ',' + y);
}
}
let d = new DemonstrateScopingProblems();
// With parameters
someCallback((n, m) => d.run(n, m));
// Without parameters
window.setTimeout(() => d.something(), 100);
- 好/坏:与第一种方法相比,内存/性能的权衡正好相反
- 好:在TypeScript中,这具有100%的类型安全性
- 好:适用于ECMAScript 3
- 好:只需键入一次实例名称
- 错误:您必须键入两次参数
- 坏:不容易使用可变参数
除了Thierry发现的回调顺序问题外,您还有一个丢失的这一行的上下文:
navigator.geolocation.getCurrentPosition(this.showPosition);
问题
您有一个典型的JavaScript问题,称为不正确的this
context。
与其他语言(如C#和Java)中的行为不同
这个
的工作原理
函数中的此
关键字确定如下:
*如果函数是通过调用.bind
创建的,则此
值是提供给绑定的参数
*如果函数是通过方法调用调用的,例如expr.func(args)
,则此
为expr
*否则
*如果代码在中,此
为未定义
*否则,此
为窗口
(在浏览器中)
让我们看看这在实践中是如何工作的:
class Foo {
value = 10;
doSomething() {
// Prints 'undefined', not '10'
console.log(this.value);
}
}
let f = new Foo();
window.setTimeout(f.doSomething, 100);
此代码将打印未定义的
(或在严格模式下引发异常)。
这是因为我们最终进入了上面决策树的最后一个分支。
调用了doSomething
函数,该函数不是bind
调用的结果,也不是在方法语法位置调用的
我们无法查看setTimeout
的代码来查看它的调用,但我们不需要这样做。
需要了解的是,所有的doSomething
方法都指向同一个函数对象。
换言之:
let f1 = new Foo();
let f2 = new Foo();
// 'true'
console.log(f1.doSomething === f2.doSomething);
我们知道,setTimeout
只能看到我们传递给它的函数,所以当它调用该函数时,
它无法知道该
提供哪个。
此
上下文已丢失,因为我们在未调用方法的情况下引用了该方法
红旗
一旦您了解了这个问题,就很容易发现它们:
class Foo {
value = 10;
method1() {
doSomething(this.method2); // DANGER, method reference without invocation
}
method2() {
console.log(this.value);
}
}
解决方案
这里有几个选项,每个选项都有自己的权衡。
最佳选择取决于该方法在questi中的频率