通过Angular中的路由路径发送数据

时间:2017-07-01 18:48:43

标签: angular routing angular-router

无论如何使用router.navigate将数据作为参数发送? 我的意思是,像this这样的例子,因为你可以看到路线有一个数据参数,但这样做它不起作用:

  public class ListViewAdapter extends BaseAdapter {

// Declare Variables

Context mContext;
LayoutInflater inflater;
private List<AnimalNames> animalNamesList = null;
private ArrayList<AnimalNames> arraylist;

public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {
    mContext = context;
    this.animalNamesList = animalNamesList;
    inflater = LayoutInflater.from(mContext);
    this.arraylist = new ArrayList<AnimalNames>();
    this.arraylist.addAll(animalNamesList);
}

public class ViewHolder {
    TextView name;
}

@Override
public int getCount() {
    return animalNamesList.size();
}

@Override
public AnimalNames getItem(int position) {
    return animalNamesList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

public View getView(final int position, View view, ViewGroup parent) {
    final ViewHolder holder;
    if (view == null) {
        holder = new ViewHolder();
        view = inflater.inflate(R.layout.listview_item, null);
        // Locate the TextViews in listview_item.xml
        holder.name = (TextView) view.findViewById(R.id.name);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    // Set the results into TextViews
    holder.name.setText(animalNamesList.get(position).getAnimalName());


    return view;
}


// Filter Class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    animalNamesList.clear();
    if (charText.length() == 0) {
        animalNamesList.addAll(arraylist);
    } else {
        for (AnimalNames wp : arraylist) {
            if (wp.getAnimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
                animalNamesList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}


////Here My problem starts : 

public static SpannableString highlightKeyword(CharSequence text, Pattern p, int fgcolor, int bgcolor) {
    SpannableString ss = new SpannableString(text);

    ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});

    int start = 0;
    int end;
    Matcher m = p.matcher(text);
    while (m.find(start)) {
        start = m.start();
        end = m.end();

        BackgroundColorSpan bgspan = new BackgroundColorSpan(bgcolor);
        ss.setSpan(bgspan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan fgspan = new ForegroundColorSpan(fgcolor);
        ss.setSpan(fgspan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        start = end;
    }

    return ss;
}


////But even did not the result word highlighted. 

因为某些数据不是有效参数。我怎样才能做到这一点?我不想用queryParams发送参数。

7 个答案:

答案 0 :(得分:294)

关于这个主题存在很多困惑,因为有很多不同的方法可以做到这一点。

以下是以下屏幕截图中使用的相应类型:

private route: ActivatedRoute
private router: Router

1)必需的路由参数:

enter image description here

2)路由可选参数:

enter image description here

3)路由查询参数:

enter image description here

4)您可以使用服务将数据从一个组件传递到另一个组件,而不使用路由参数。

有关示例,请参阅:https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

我有一个这方面的人:https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview

答案 1 :(得分:44)

Angular 7.2.0附带了一种新方法

https://angular.io/api/router/NavigationExtras#state

发送:

this.router.navigate(['action-selection'], { state: { example: 'bar' } });

收到:

constructor(private router: Router) {
  console.log(this.router.getCurrentNavigation().extras.state.example); // should log out 'bar'
}

您可以在此处找到一些其他信息:

https://github.com/angular/angular/pull/27198

上面的链接包含此示例,可能会有用: https://stackblitz.com/edit/angular-bupuzn

答案 2 :(得分:6)

你可以用它。 Angular2 + / 4/5 - 使用数据导航 https://github.com/Hipparch/Angular2-navigate-with-data

答案 3 :(得分:4)

最新版本的angular(7.2 +)现在可以选择使用 NavigationExtras 传递其他信息。

主页组件

import {
  Router,
  NavigationExtras
} from '@angular/router';
const navigationExtras: NavigationExtras = {
  state: {
    transd: 'TRANS001',
    workQueue: false,
    services: 10,
    code: '003'
  }
};
this.router.navigate(['newComponent'], navigationExtras);

newComponent

test: string;
constructor(private router: Router) {
  const navigation = this.router.getCurrentNavigation();
  const state = navigation.extras.state as {
    transId: string,
    workQueue: boolean,
    services: number,
    code: string
  };
  this.test = "Transaction Key:" + state.transId + "<br /> Configured:" + state.workQueue + "<br /> Services:" + state.services + "<br /> Code: " + state.code;
}

输出

enter image description here

希望这会有所帮助!

答案 4 :(得分:0)

为此我在互联网上发现的最好的是ngx-navigation-with-data。 对于将数据从一个组件导航到另一组件而言,这非常简单且有益。 您只需要导入组件类并以非常简单的方式使用它即可。 假设您有住所和关于组件,然后想要发送数据

家庭组件

echo "some text" >> file.txt

关于组件

import { Component, OnInit } from '@angular/core';
import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';

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

constructor(public navCtrl: NgxNavigationWithDataComponent) { }

 ngOnInit() {
 }

 navigateToABout() {
  this.navCtrl.navigate('about', {name:"virendta"});
 }

}

对于任何查询,请遵循https://www.npmjs.com/package/ngx-navigation-with-data

留言寻求帮助。

答案 5 :(得分:0)

@ dev-nish您的代码可以进行一些小的调整。 制作

const navigationExtras: NavigationExtras = {
  state: {
    transd: 'TRANS001',
    workQueue: false,
    services: 10,
    code: '003'
  }
};

进入

let navigationExtras: NavigationExtras = {
  state: {
    transd: '',
    workQueue: ,
    services: ,
    code: ''
  }
};

然后,如果您要专门发送某种类型的数据(例如,由于表单填写而导致的JSON),则可以按照前面说明的相同方式发送数据。

答案 6 :(得分:0)

在navigationExtra中,我们只能传递某些特定名称作为参数,否则它将显示错误,如下所示: 对于Ex-,​​我想在路由器导航中传递客户密钥,然后像这样传递-

this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});

但是它显示出如下错误:

Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
  Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'

解决方案: 我们必须这样写:

this.Router.navigate(['componentname'],{state: {customerkey:response.key}});