标签: angular2-services

在Angular2中将类导出为接口

有没有办法将类导出为接口,然后在Angular 2中的另一个模块中导入该接口?我需要能够在一些组件的构造函数中注入类,例如应该注册为提供者.

typescript angular2-services angular

1
推荐指数
1
解决办法
1194
查看次数

如何处理 Angular 2 CanActivate Route Guards

我已经在我的应用程序上实现了 Route Guards。在用户访问仪表板路由之前,我检查了用户是否已登录。

登录后用户访问仪表板工作正常,但如果用户尝试在未登录的情况下访问路线仪表板,则会出现空白页面。CanActivate Guard 被执行并返回 false。

但是,如果 CanActivate 失败,我想将用户重定向到日志记录页面。

如果 Route Guard 失败,如何将用户重定向到另一个路由?

这就是我所遵循的

import { Routes, RouterModule } from '@angular/router';
import { AccountPage } from './account-page';
import { LoginRouteGuard } from './login-route-guard';
import { SaveFormsGuard } from './save-forms-guard';
const routes: Routes = [
{ path: 'home', component: HomePage },
{
path: 'accounts',
component: AccountPage,
canActivate: [LoginRouteGuard],
canDeactivate: [SaveFormsGuard]
}
];
export const appRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(routes);
Run Code Online (Sandbox Code Playgroud)

import { CanActivate } from '@angular/router';
import …
Run Code Online (Sandbox Code Playgroud)

angular2-routing angular2-services angular

1
推荐指数
1
解决办法
4552
查看次数

如何在listview angular2 nativescript中解析这个json结构

json结构:

{
  "Employee": [
       {"id":1,"name":"Dan" },
       {"id":2,"name":"Stack" },
       .....
    ]
}
Run Code Online (Sandbox Code Playgroud)

app.component.ts:

 ngOnInit() {
 console.log("first", "Test");

    this.globalReader.getObjectData()
      .subscribe(data => this.getData = JSON.stringify(data),  ---> Response printed successfully here.I'm able to print it in label.
       error => alert(error),
       () => console.log("finished")

      );      

  }
Run Code Online (Sandbox Code Playgroud)

编辑:

零件:

  <label text ="{{getData }}" ></label>



  getObjectData() {

    return this._http.get('/page/emp.json')
      .map((response :Response) => response.json());

  }  
Run Code Online (Sandbox Code Playgroud)

之后,我不知道如何解析json并在listview中为此结构打印它.我提到了一些视频和杂货申请.但我仍然无法得到结果.我非常困惑arrayname员工.

我需要name在listview中只打印from响应.

typescript nativescript angular2-services angular2-nativescript angular

1
推荐指数
1
解决办法
1036
查看次数

当用户离开应用程序时删除会话存储

我想在用户关闭我的应用程序时执行以下代码。

ngOnDestroy(): void {
    sessionStorage.clear();
}
Run Code Online (Sandbox Code Playgroud)

简而言之,一旦用户离开我的应用程序,我想清除我的应用程序的 sessionStorage,但当用户刷新应用程序时,数据将被保留。

当应用程序关闭时 OnDestroy 似乎不会触发。

我也试过下面的代码

ngOnInit() {
   window.onbeforeunload = function () {
     sessionStorage.clear();
     return ''
   }
}
Run Code Online (Sandbox Code Playgroud)

我知道这不是正确的地方,但刷新时也有清晰的数据:(而且这不适用于每个浏览器。

我可以在哪里放置此代码以获得我正在寻找的行为,或者是否有更好的方法来完成我想要完成的任务?

session-storage angular2-services angular

1
推荐指数
1
解决办法
1万
查看次数

这个Angular 2应用程序中的服务层次结构究竟如何工作?

我是Angular 2的新手,我有关于服务的以下问题.

进入主视图(与app.component.ts类相关的一个)我遇到这种情况:

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-md-8 col-md-offset-2">
      <app-new-account (accountAdded)="onAccountAdded($event)"></app-new-account>
      <hr>
      <app-account
        *ngFor="let acc of accounts; let i = index"
        [account]="acc"
        [id]="i"
        (statusChanged)="onStatusChanged($event)"></app-account>
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

所以在这个视图中我有2个子组件(app-new-accountapp-account).

进入主AppComponent组件类我有:

import {Component, OnInit} from '@angular/core';
import {AccountsService} from './accounts.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AccountsService]
})
export class AppComponent implements OnInit {

  accounts: {name: string, status: string}[] = [];

  // Injectiong the …
Run Code Online (Sandbox Code Playgroud)

javascript javascript-framework angular2-services angular

1
推荐指数
1
解决办法
221
查看次数

多个 ngx 分页错误 - 角度 2

我正在为我的一个项目使用 angular 2,我正在使用 ngx-pagination 对表进行分页。我的页面结构是这样的

parent->child1=table1
        child2-table-2
        child-table-3
        child4-table-4
Run Code Online (Sandbox Code Playgroud)

每个孩子都调用自己的休息请求并填充表格。我在父级中使用了子组件,如下所示

parent->child1=table1
        child2-table-2
        child-table-3
        child4-table-4
Run Code Online (Sandbox Code Playgroud)

等等

在每个子组件中,我都使用 ngx-pagination 作为

<tr *ngFor="let data of exitProcessPendingList | paginate: { itemsPerPage: 7, currentPage: pgNumber};let i=index">

<pagination-controls (pageChange)="pgNumber = $event"></pagination-controls>
Run Code Online (Sandbox Code Playgroud)

每个孩子都有唯一的 pageNumber 变量;

现在我面临的问题是,当我尝试更改一个表的页码时,它也会影响其他子表。如果我单击第一个表的第 2 页,所有其他表都将当前页更改为第 2 页.我做错了什么?我做的方式有什么问题吗?

angular2-directives angular2-template angular2-services angular

1
推荐指数
1
解决办法
1179
查看次数

Angular 2对预检请求的响应未通过访问控制检查:没有'Access-Control-Allow-Origin'标头

我是Angular2的新手.我正在尝试将POST方法调用到我的.net核心API.它与Postman一起正常工作.但是当我从我的角度2服务调用它时它会出错.

在此输入图像描述

这是我的api.service.ts

import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { Headers, Http, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { JwtService } from './jwt.service';

@Injectable()
export class ApiService {
  constructor(
    private http: Http,
    private jwtService: JwtService
  ) {}

  private setHeaders(): Headers {
    const headersConfig = {
      'Content-Type': 'application/json',
      'Accept': 'application/json', 
      'Access-Control-Allow-Origin': '*'
    };      

    if (this.jwtService.getToken()) {
      headersConfig['Authorization'] = `Token ${this.jwtService.getToken()}`;
    }
    return new Headers(headersConfig);
  } …
Run Code Online (Sandbox Code Playgroud)

angular2-services asp.net-core-webapi

1
推荐指数
1
解决办法
5692
查看次数

在Angular 2中添加日期/时间服务

我正在尝试在Angular 2中建立一个非常基本的服务。目标是在用户单击按钮时显示当前日期和时间。当我使用下面的代码时,出现以下错误:

Error during evaluation of "click" ORIGINAL EXCEPTION: TypeError: l_context.whatTime is not a function

时间部分:

@Component({
    template: `
      <h1>Time Test</h1>
      <button (click) = "whatTime()">Time</button>
      <h2>{{now}}</h2>
         `
})

    export class TimeComponent {
      now = Date();
      constructor(public timeService: TimeService) {
        this.now = timeService.whatTime();
    }
}
Run Code Online (Sandbox Code Playgroud)

服务:

@Injectable()
    export class TimeService {

      whatTime() {
      return new Date();
    }
}
Run Code Online (Sandbox Code Playgroud)

对我在做什么错有任何想法吗?

observable rxjs angular2-services angular

0
推荐指数
1
解决办法
4924
查看次数

angular2路由器在订阅方法中变为未定义

正如标题所解释的那样,当router对象在subscribe成员内部被调用时,该对象变得不确定.

我来告诉你一些代码:

export class AuthComponent implements OnInit {
   password = '';
   email = ''; 

  constructor(
      private _router: Router,
      private authService: AuthService
  ) { }


  sendLogin(): void {
       this.authService.login(this.email, this.password)
                   .subscribe(function(token){
                     console.log("Success Response" + token)
                     this.token = token
                     // TOKEN Here is good
                     // now I want to change my page, but
                     // _router -> undefined
                     this._router.navigate(['/dashboard']);

                   },
                     error =>  console.log(error));
     }
Run Code Online (Sandbox Code Playgroud)

sendLogin()提交表单时调用该方法.表格中的每个变量都很好.

这个过程subscribe完美,但后来 this._router.navigate(['/dashboard']); 给了我:

EXCEPTION:无法读取undefined的属性'navigate'

有任何想法吗 ?

angular2-routing angular2-services angular2-observables angular

0
推荐指数
1
解决办法
471
查看次数

从angular2应用程序调用在Docker容器中运行的服务

我有一个用Angular2开发的UI应用程序。我也有一些在Spring Boot中开发的服务。我正在尝试从Angular应用程序调用Spring Boot服务。

以下是我的docker-compose.yml

version: '2'
networks:
  mynet:
services:
  ui:
    image: uiimg
    networks:
      - mynet
    ports:
      - "4200:4200"
  srvc:
    image: scservice
    networks:
      - mynet
    ports:
      - "8080:8080"
  testsrvc:
    image: testsrvc
    networks:
      - mynet
    ports:
      - "8081:8081"      
Run Code Online (Sandbox Code Playgroud)

这就是我从angular调用“ srvc”定义的服务的方式。

return this.http.get("http://srvc:8080/test").map(result => result.json());
Run Code Online (Sandbox Code Playgroud)

但是我收到错误srvc:8080 / test无法加载资源:net :: ERR_NAME_NOT_RESOLVED

但是,我可以从“ testsrvc”中的另一个服务调用http:// srvc:8080 / test,而不会出现任何问题。

我的理解是,由于UI请求源自浏览器,因此它无法知道“ srvc”是什么,而由于“ testsrvc”也运行在容器中,因此可以链接到“ srvc”

因此,我应该如何从角度调用“ srvc”?

PS:我尝试了http:// srvc:8080 / testhttp:// srvc / test 都不起作用。

容器中的角度应用程序已启动并正在运行,我能够从http:// localhost:4200访问它

docker docker-compose angular2-services angular

0
推荐指数
1
解决办法
1413
查看次数