已经和Angular v1合作已经有一段时间了,自从Angular v2进入测试版以来,我一直在玩这个游戏.
现在我已经有了这段代码,但无法让它工作,真的不知道为什么.不知何故,当我打印{{profileUser | json}}一切正常(profileUser是一个对象).
但是当我想打印该对象的子项时(例如{{profileUser.name}}或{{profileUser.name.firstName}}),Angular会抛出以下错误:
EXEPTION: TypeError: undefined is not an object (evaluating 'l_profileUser0.name') in [ {{profileUser.name}} in ProfileComponent@4:11.
这对我来说真的很混乱,应该只是最简单的事情之一..刚开始使用TypeScript btw ..
这是一些代码 - ProfileService.ts:
import { Injectable } from 'angular2/core';
import { Headers } from 'angular2/http';
import { API_PREFIX } from '../constants/constants';
import { AuthHttp } from 'angular2-jwt/angular2-jwt';
import 'rxjs/add/operator/map';
@Injectable()
export class ProfileService {
API_PREFIX = API_PREFIX;
constructor(private _authHttp:AuthHttp) {
}
getProfileData(username:string):any {
return new Promise((resolve, reject) => …Run Code Online (Sandbox Code Playgroud) 我正在制作一个示例应用程序来连接到离线2 in typescript中的websocket服务器.回到repo
我的要求是在应用程序启动期间进行websocket连接
我正在使用angular2-websocket来创建连接.
参考文献:
http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html
http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html
我收到错误"无法解析'$ WebSocket'的所有参数(字符串,数组,?).确保所有参数都使用Inject进行修饰或具有有效的类型注释,并且'$ WebSocket'使用Injectable进行修饰. "
代码: app.ts
import {App, Platform} from 'ionic-framework/ionic';
import {TabsPage} from './pages/tabs/tabs';
import {ConnectionService} from './framework/connection/connection-service'
import {$WebSocket} from 'angular2-websocket/angular2-websocket';
import {bootstrap} from 'angular2/platform/browser';
// https://angular.io/docs/ts/latest/api/core/Type-interface.html
import {Type} from 'angular2/core';
@App({
template: '<ion-nav [root]="rootPage"></ion-nav>',
config: {}
})
export class MyApp {
rootPage: Type = TabsPage;
constructor(platform: Platform, private conn : ConnectionService) {
platform.ready().then(() => {
this.conn.connect();
});
}
}
bootstrap(MyApp, [$WebSocket, ConnectionService]);
Run Code Online (Sandbox Code Playgroud)
import {Injectable, Component, …Run Code Online (Sandbox Code Playgroud) 我注意到我的Angular 2应用程序在使用一段时间后变得非常缓慢.
我分析了CPU时间,发现有大量的变更检测执行正在进行中.
页面加载后的CPU配置文件...
...与页面使用一段时间后的CPU配置文件进行比较.
我EventEmitter在很多组件之间使用了很多不同的服务进行通信.
经过一段时间的测试,似乎窗口滚动事件的发射器会导致很大一部分重负载.
使用页面一段时间后CPU轮廓而不发出滚动事件:
这里执行服务:
@Injectable()
export class WindowService {
@Output() scrolled$: EventEmitter<WindowScrolled> = new EventEmitter();
private scrollDebounceTime = 25;
constructor() {
this.addEvent(window, 'scroll', this.debounce((event) => {
this.scrolled$.emit(new WindowScrolled(window.scrollX, window.scrollY));
}, this.scrollDebounceTime));
}
// ... other functions
}
Run Code Online (Sandbox Code Playgroud)
EventEmitter错误,我该如何正确使用它?另外我发布了网格树组件,因为更改可能是由我的组件构建的递归树结构引起的.
@Component({
selector: 'hierarchy-grid-tree',
moduleId: __moduleName, // use `__moduleName` from System.js for relative styleUrls and templateUrls
styleUrls : [`hierarchy-grid.css`],
template: `<div class="flex-container">
<div class="flex-item" *ngFor="#node of nodes; …Run Code Online (Sandbox Code Playgroud) 我是观察者的新手,并在Angular2博客中尝试了Christoph Burgdorf的Observables的基本自动完成变体.运行此代码会产生:
EXCEPTION:TypeError:无法读取未定义的属性'Symbol(Symbol.iterator)'
在ingredientservice ... rawsearch发出REST get调用之后.警报还会弹出[object Object]消息.我已经验证了端点运行正常.
任何有关如何调试此建议的建议将不胜感激.
ingredientservice.ts等待对文本字符串进行更改,对其进行去抖动并执行REST调用以从端点获取自动完成匹配.
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map';
@Injectable()
export class IngredientService {
endpoint_url: String = "http://localhost:5000/ingredient/";
results: Observable<Array<string>>;
constructor(private http: Http) { }
search(terms: Observable<string>, debounceDuration = 400) {
return terms.debounceTime(debounceDuration)
.distinctUntilChanged()
.switchMap(term => this.rawSearch(term));
}
getData: Object[];
rawSearch(term: string) {
console.log(term);
this.http.get(this.endpoint_url + term)
.subscribe(
res => {
this.getData = res.json(); …Run Code Online (Sandbox Code Playgroud) 我有一个叫api的服务
getItems(itemId: number): Observable<any> {
return this.http.get(url, headers)
.map(this.extractDataSingle)
.catch(this.handleError)
}
Run Code Online (Sandbox Code Playgroud)
如果服务器以4xx响应,catch则调用该部件.这是我的handleError方法.
private handleError = (error: any) => {
//Here I want to redirect to login.
}
Run Code Online (Sandbox Code Playgroud)
我想重定向到该login页面.简单的打字this._router.navigate(['Login']);不起作用,因为我必须返回一个Observable.返回一个空的Observable return Observable.empty;也不起作用,因为我的订阅者收到错误:Cannot read property 'subscribe' of undefined.
如何实现我将用户重定向到登录页面?当然,我可以更改我的订阅者以捕获错误并通过我的订阅者重定向.但我认为最好在我的服务中处理错误.
我也对如何处理4xx错误的完全不同的解决方案持开放态度.
编辑:感谢@GüntherZöschbauer.这return Observable.of([]);正是我所需要的.但是,请注意this.为了有机会获得router在 handleError方法中使用bind(this)的.catch(this.handleError.bind(this))
getItems(itemId: number): Observable<any> {
return this.http.get(url, headers)
.map(this.extractDataSingle)
.catch(this.handleError.bind(this))
}
Run Code Online (Sandbox Code Playgroud)
否则你无权访问你的router.
我是Angular 2和Observables的新手,所以如果我的问题很简单,我会道歉.无论如何,我正在尝试使用RxJS测试Angular 2 HTTP客户端.虽然我让它工作,但我需要为我正在处理的服务添加更多逻辑.基本上我想要一个映射函数将我从我连接的Web服务接收的对象转换为我在Angular中的模型对象.
这是有效的代码:
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import { Observable } from 'rxjs/Observable';
import { Person } from '../models/person';
@Injectable()
export class PersonsService {
constructor(private http: Http) { }
private personsUrl = 'http://localhost/api/persons';
getPersons(): Observable<Person[]> {
return this.http.get(this.personsUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
if(res.status < 200 || res.status >= 300) {
throw new Error('Bad response status ' + res.status);
}
let body = res.json();
return body.data || …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Http服务进行ajax调用,这工作正常.
现在我想处理失败案件.例如,如果我们得到404或任何其他错误.
我使用以下代码.
import {Component,Inject} from '@angular/core';
import {Http, Response,HTTP_PROVIDERS} from '@angular/http';
import {DoService} from './service';
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';
@Component({
selector: 'comp-one',
template: `<h2>My First Angular 2 App</h2>{{data}}
<input type="button" (click)="doSomething()" value="Do Http"/>`
})
export class ComponentOne {
constructor(public _http:Http){
console.log("It is from ComponentOne constructor..");
this._http = _http;
}
data:Object;
doSomething(){
console.log("It is from doSomething ComponentOne");
let temp:any = this._http.get('people.json')//people.json is not exist, intendedly maing any error
.map(res => res.json())
.catch((err:any)=>{ console.log("Something is wrong..")});// If i keep this line …Run Code Online (Sandbox Code Playgroud) 我已经实现了通过我的HTTP请求中的catch获取API错误返回的值.我现在的问题是,当我调用服务时,如何获取组件中HTTP catch的返回值.
这是我的HTTP服务中的代码:
login(username,password){
let headers = new Headers();
headers.append('Content-Type','application/json');
return this.http.post(this.configEnvironment.url() + "oauth/access_token",
JSON.stringify(
{
username: username,
password: password,
grant_type: "password",
client_id: "xxxx",
client_secret: "xxxxx"
}
),
{ headers }
)
.map(res => res.json())
.catch((err:Response) => {
let details = err.json();
return Observable.throw(new Error(details));
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的login.component中的代码:
this.loginService.login(this.model.username,this.model.password)
.subscribe(
data => console.log("data"),
error => {
console.log(error);
},
() => console.log("Finished")
);
Run Code Online (Sandbox Code Playgroud)
在chrome开发人员工具中,这是console.log的返回:
Error: [object Object](…)
Run Code Online (Sandbox Code Playgroud)
但是http服务catch的实际返回是:{"error":"invalid_credentials","error_description":"invalid credentials"}这是我想进入login.component
我想将逻辑从组件转移到服务.但我发现我无法在服务中获得routeParams.
我的组件看起来像
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { MyService } from '../services/my.service';
@Component({
moduleId: module.id,
templateUrl: 'my.component.html',
styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
constructor(private myService: MyService, private route: ActivatedRoute) {;}
public ngOnInit() {
this.route.params
.subscribe((params: Params) => {
debugger;
console.log(params);
});
this.myService.getParams()
.subscribe((params: Params) => {
debugger;
console.log('Return1:');
console.log(params);
}, (params: Params) => {
debugger;
console.log('Return2:');
console.log(params);
}, () => {
debugger;
console.log('Return3:');
});
}
};
Run Code Online (Sandbox Code Playgroud)
我的服务看起来像 …
我正在使用启用了Pager的后端服务器(Java Spring).我在HTTP调用上每页加载100条记录.
在angular2服务上,它使用"?page = 1&size = 100"作为初始调用的API调用,而在客户端大小的寻呼机上,它显示10并且最多移动10页,这很好.但我无法从服务器加载下一块数据.我检查了ServerDataSource并使用了.setPaging(1,100).
如何加载下一个数据块(2-200)以及如何实现此目的.任何提示都会有所帮助.
@Injectable()
export class AmazonService extends ServerDataSource {
constructor(protected http: Http) {
super(http);
}
public getAmazonInformation(page, size): Observable<Amazon[]> {
let url = 'http://localhost:8080/plg-amazon?page=1&size=100';
this.setPaging(1, 100, true);
if (this.pagingConf && this.pagingConf['page'] &&
this.pagingConf['perPage']) {
url +=
`page=${this.pagingConf['page']}&size=${this.pagingConf['perPage']}`;
}
return this.http.get(url).map(this.extractData).catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
angular ×10
javascript ×2
rxjs ×2
angularjs ×1
ionic2 ×1
pagination ×1
performance ×1
typescript ×1
web ×1