上下文
我正在编写一个 Angular2 应用程序,我希望在其中使用多个服务来访问不同的端点。我希望每个服务都缓存其数据,以减少发出的请求数量,并允许多个组件在将数据发送到端点之前修改缓存中的数据。
编码
@Injectable()
export class MyService {
private items: any;
constructor (private http: Http) {
this.items = [];
}
getItems () {
if(!this.items) {
return this.http.get(this.endpoint).map((data) => {
this.items = data;
return data;
});
} else {
return Observable.of(this.items);
}
}
addItem (item) {
this.items.push(item);
}
saveItems () {
return this.http.put(endpoint, this.items);
}
}
Run Code Online (Sandbox Code Playgroud)
那么 Component1 可能会这样做:
userClickedAddItem (item) {
this.myService.addItem(item);
}
Run Code Online (Sandbox Code Playgroud)
Component2 可能会这样做:
userClickedSave () {
this.myService.saveItems().subscribe((items) => {
// Do something
});
}
Run Code Online (Sandbox Code Playgroud)
然后在组件的模块中我正在做类似的事情
@NgModule({ …Run Code Online (Sandbox Code Playgroud) 在我的 Angular2 应用程序中,我从 REST API 获取响应并操作它们以便在用户界面中显示它们。
我根据以下教程编写了我的应用程序。
这是我从服务器获取响应的方法
getTendersByCategory(categoryName: string){
console.log("get tenders by category "+categoryName);
let tendersByCategory = this._http
.get(this._endpointUrl + "tender/get-by-category-name/" + categoryName)
.map(mapTenders)
.catch(handleError);
return tendersByCategory;
}
Run Code Online (Sandbox Code Playgroud)
以下函数用于操作响应
function mapTenders(response: Response): Tender[] {
console.log('tender.service.ts -> mapTenders');
/*if(response.status == 204){
console.log("response = 204 - No content in response");
return null;
}*/
return response.json().map(toTender);
}
function toTender(r: any): Tender {
console.log('tender.service.ts -> toTender');
let tender = <Tender>({
id: r.id,
name: r.name,
publisher: r.publisher,
});
return tender;
}
function handleError(error: …Run Code Online (Sandbox Code Playgroud) angular2-services angular2-http angular2-observables angular
我已经搜索了很长时间来了解如何订阅一个值不断更新的数组。
我需要了解如何正确设置我的 Angular 2+ 服务 observable 并在我的组件中正确订阅它。请假设代码的所有其他部分都能正常工作。
@Injectable()
export class AutocompleteService {
searchTerm: string;
results = [];
observe$ = Observable.from(this.results);
searchTest(term){
this.searchTerm = term.toLowerCase();
if(this.searchTerm.length > 2){
this.recruiters.forEach(function(el){
if(el.name.toLowerCase().indexOf(term) != -1) {
this.results.push(el);
}
});
}
}
getCurrentResults():Observable<Object> {
return this.observe$;
}
Run Code Online (Sandbox Code Playgroud)
服务中的一切都按预期工作。如果我登录,term我会从我的组件中获取用户输入。或者results匹配搜索结果后的数组被推送到它上面。
@Component({
selector: 'autocomplete',
templateUrl: './autocomplete.component.html',
providers: [AutocompleteService]
})
export class AutocompleteComponent implements OnInit{
constructor(private autocompleteService: AutocompleteService){}
value: string = '';
searchControl = new FormControl();
// fired when input happens
getResults(event){
this.autocompleteService.searchTest(event.target.value);
this.autocompleteService.getCurrentResults().subscribe(
value …Run Code Online (Sandbox Code Playgroud) 如何根据 angular 2 中的用户区域设置格式化数字
示例 - 如果用户语言环境为德语(德国),则数字显示为 1.234,56
我正在使用 Angular 4、NPM、Node.js 和 Angular CLI 进行一个项目。
我需要在@Injectable没有 HTTP 请求的情况下将JSON 加载到 Angular 服务中(使用),即它总是作为包的一部分在本地加载,而不是从服务器检索。
到目前为止,我发现的所有内容都表明您要么必须修改项目typings.d.ts文件,要么使用 HTTP 请求从/assets文件夹或类似文件中检索它,这两种方法都不适合我。
我想要完成的是这个。给定以下目录结构:
/app
/services
/my-service
/my.service.ts
/myJson.json
Run Code Online (Sandbox Code Playgroud)
我需要my.service.ts正在使用的服务@Injectable来加载 JSON 文件myJson.json。对于我的特殊情况,文件旁边会有多个 JSON 文件,这些my.service.ts文件都需要加载。
澄清一下,以下方法对我不起作用:
网址:https : //stackoverflow.com/a/43759870/1096637
摘抄:
// Get users from the API
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
Run Code Online (Sandbox Code Playgroud)
网址: …
我有一个组件叫 customComponent
import {Component} from '@angular/core';
import { appService } from './app.service';
@Component({
selector: 'custom-root',
template: `<h1>how</h1>
<ul *ngFor="let hero of heroes"><li>{{hero}}</li></ul>`,
})
export class CustomComponent {
heroes = ['first','second','third'];
//heroes;
value: string = "";
// constructor(appService: appService) { }
/* ngOnInit(): void {
this.value = this._appService.getApp();
} */
}
Run Code Online (Sandbox Code Playgroud)
在appService我有
import {
Injectable
} from '@angular/core';
@Injectable()
export class appService {
getApp(): string {
return "Hello world";
}
}
Run Code Online (Sandbox Code Playgroud)
在app.module.ts我导入应用程序服务
import { appService } from …Run Code Online (Sandbox Code Playgroud) 我正在使用表格
<form [formGroup]="form">
<input type="text" value={{userDetails.first_name}} formControlName = "firstName">
<button type="submit" data-action="save" (click)="onSubmit(form.value)">
</form>
Run Code Online (Sandbox Code Playgroud)
这里的userDetails.first_name价值是汤姆。它在文本框内的 UI 上可见;但是当我提交表单时form.firstName给了我空值。
我想在 html 上以年为单位显示月数。我的过滤器将月数作为输入,它应该返回年数。
例如:如果以 12 作为输入,则应将转换后的值返回为 1 年。如果超过 1 年,则应返回“2 年”。
我的管道包含:
import { Pipe, PipeTransform} from '@angular/core';
@Pipe({name : 'displayMonthsInYears '})
export class DisplayMonthsInYears implements PipeTransform{
transform(noOfMonths : number) : any {
if(noOfMonths > 12){
return (noOfMonths / 12 + $translate.instace('YEARS'));
}
return (noOfMonths / 12 + $translate.instace('YEAR'));
}
}
Run Code Online (Sandbox Code Playgroud)
和 html 是:
<div class="text-left">
{{ contractDuration | displayMonthsInYears }}
</div>
Run Code Online (Sandbox Code Playgroud)
我不知道如何做到这一点。请帮忙。
我正在使用 AGM(角度谷歌地图)来制作地图。我已经放了一个 getCurrentLocation 按钮,它返回我当前位置的纬度和经度。我能够将标记更新到那个地方,但我的地图没有导航到那个特定位置。这是我的示例代码。
getCurrentLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((response) => {
this.setPosition(response);
}, function () {
alert("Unable to get the GPS location");
}, { maximumAge: 60000, timeout: 5000, enableHighAccuracy: true });
};
}
Run Code Online (Sandbox Code Playgroud)
这是我的 setPosition 方法
setPosition(position: Position) {
this.marker.lat = position.coords.latitude;
this.marker.lng = position.coords.longitude;
//What to do here to move screen to this marker position
}
Run Code Online (Sandbox Code Playgroud)
我正在创建 Progressive-web-app 应用程序,我想将用户信息存储在本地设备中。那么,我该怎么做呢。如何存储用户登录信息,让他不必一次又一次地登录